<?php
/**
 * Created by PhpStorm.
 * User: 35083
 * Date: 2019/6/27
 * Time: 10:12
 */

use think\Db;
use think\Session;

/**
 * 获取课程信息
 * @param unknown $class_id
 * @return multitype:
 */
function getClasslistInfo($class_id)
{
    if (empty($class_id)) {
        return [];
    }
    $classlistModel = new \app\admin\model\Classlist();
    return $classlistModel->getDataForWhere(array('id' => $class_id));
}

/**
 * 判断是否已经加入一个课程ID
 * @param unknown $uid 用户ID
 * @param unknown $class_id 课程ID
 * @return number 0表示未加入 1表示已经加入
 */
function isJoinInClass($uid, $class_id)
{
    $classUserjoinModel = new \app\admin\model\ClassUserjoin();
    $flag = $classUserjoinModel->getDataForWhere([
        'uid' => $uid,
        'classid' => $class_id
    ]);
    if (empty($flag)) {
        return 0;
    } else {
        return 1;
    }
}

/**
 * 批量加入打卡记录
 * @param unknown $data
 * @return mixed
 */
function addPlanCheckIn($uid, $classlistInfo)
{

    if (empty($classlistInfo['days'])) {
        return 0;
    }
    if (empty($classlistInfo['task_time'])) {
        return 0;
    }
    $totle = $classlistInfo['days'];
    $startTime = strtotime($classlistInfo['task_time']);
    for ($i = 0; $i < $totle; $i++) {
        if ($i == 0) {
            $time = $startTime;
        } else {
            $time = strtotime("+{$i}days", $startTime);
        }
        $year = date("Y", $time);
        $month = date("m", $time);
        $day = date("d", $time);
        $data = array(
            'uid' => $uid,
            'classid' => $classlistInfo['id'],
            'y' => $year,
            'm' => $month,
            'd' => $day,
            'day' => $i + 1,
            'type' => 0,
            'info' => "",
        );
        $table = 'class_checkin';
        $sql = generaSql("t_" . $table, $data);
        \think\Db::query($sql);
    }
    return 0;
}

/**
 * 判断一个课程是否已经购买 支付
 * @param unknown $uid 用户ID
 * @param unknown $classid 课程ID
 * @param unknown $ty 类型0课程 1是商品
 * @return 0未支付  1表示已经支付
 */
function isClasslistPay($uid, $classid, $ty = 0)
{
    $sql = "select * from t_pay_order where uid={$uid} and classid ={$classid} and ty={$ty} and stat=1";
    $list = \think\Db::query($sql, []);
    if (empty($list)) {
        return 0;
    }

    return 1;
}

/**
 * 获取一个用户最近dataid抓取的数据
 * @param $uid
 * @param $dataid
 * @return array
 */
function getSleepDataLast($uid, $dataid)
{
    $sql = "select * from t_sleep where uid={$uid} and dataid ={$dataid} order by id desc limit 1";
    $list = \think\Db::query($sql, []);
    if (empty($list)) {
        return array();
    }
    return $list[0];
}

function getLastTaskLogForParam($uid, $dataid)
{
    $param = array('uid' => $uid, 'dataid' => $dataid);
    $sql = "select * from t_task_log where param='" . json_encode($param, true) . "' order by id desc limit 1";
    $list = \think\Db::query($sql, []);
    if (empty($list)) {
        return array();
    }
    return $list[0];
}

/**
 * 加入一个课程，并返回加入ID
 * @param unknown $data
 */
function joinInClass($data)
{
    $classUserjoinModel = new \app\admin\model\ClassUserjoin();
    return $classUserjoinModel->add($data);
}

/**
 * 批量判断当前用户是否已经 加入了改课程计划
 * @param unknown $lists 课程列表
 * @param unknown $uid 用户ID
 * @return multitype:|number
 */
function addIsJoinClasslistStatus($lists, $uid)
{
    if (empty($lists)) {
        return array();
    }
    static $allTmpData = array();//静态变量array('stats'=>0)
    foreach ($lists as $key => $val) {
        if ($allTmpData[$val['id']]) {
            $val['joinStats'] = $allTmpData[$val['id']]['stats'];
            $lists[$key] = $val;
            continue;
        }
        $temp = isJoinInClass($uid, $val['id']);
        $allTmpData[$val['id']] = array('stats' => $temp);
        $val['joinStats'] = $temp;
        $lists[$key] = $val;
    }
    return $lists;
}

/**
 * 用户挑战打卡
 * @param $userinfo 当前用户数据
 * @return bool
 */
function userSign($userInfo, $classCheckinInfo)
{
    $time = time();
    $currTime = date("Y-m-d H:i:s");

    Db::startTrans();
    //修改打卡数据
    $classCheckinModel = Db::table("t_class_checkin");
    $update = array(
        'ctime' => $currTime,
        'type' => 1,
    );
    $where = array(
        'id' => $classCheckinInfo['id']
    );
    $resultCheckin = $classCheckinModel->where($where)->update($update);
    if ($resultCheckin || $resultCheckin == 0) {
        Db::commit();
        return true;
    }
    Db::rollback();
    return false;

}

/**
 * 用户获取他自己一个课程的打卡记录
 * @param $uid 用户ID
 * @param $class_id 课程ID
 * @return array
 */
function getCheckinList($uid, $class_id)
{
    $classMissionModel = new \app\admin\model\ClassCheckin();
    $list = $classMissionModel->getDataForWheres(array(
        'classid' => $class_id,
        'uid' => $uid,
    ), '*', "day asc");
    return $list;
}

/**
 * 在一个课程打卡列表中 判断今天是第几天任务
 * @param $classCheckinList
 * @return 0表示任务已经完成
 */
function getTaskTodayNum($classCheckinList)
{
    $today_task_index = 0;
    if (!empty($classCheckinList)) {
        $year = date("Y");
        $month = date("m");
        $day = date("d");
        foreach ($classCheckinList as $key => $val) {
            if ($val['y'] == $year && $val['m'] == $month && $val['d'] == $day) {
                $today_task_index = $val['day'];
                break;
            }
        }
    }
    return $today_task_index;
}

/**
 * 获取所有的自然音分类函数
 * @return array
 * @throws \think\db\exception\DataNotFoundException
 * @throws \think\db\exception\ModelNotFoundException
 * @throws \think\exception\DbException
 */
function getAllMusicType()
{
    $Model = new \app\admin\model\MusicType();
    return $Model->getDataForWheres([], "id,name", "sorts asc");
}

/**
 * 获取所有的文章分类
 * @return array
 * @throws \think\db\exception\DataNotFoundException
 * @throws \think\db\exception\ModelNotFoundException
 * @throws \think\exception\DbException
 */
function getAllArticleType()
{
    $Model = new \app\admin\model\ArticleType();
    return $Model->getDataForWheres([], "*", "pid asc,sorts asc");
}

function getAllHospArticleType($bigType = 1)
{
    $Model = new \app\admin\model\HospArticleType();
    return $Model->getDataForWheres(['bigtype' => $bigType], "*", "pid asc,sorts asc");
}

function getHospBigTypeArticle()
{
    return [
        ['id' => 1, 'name' => "专家讲堂"],
    ];
}

/**
 * 获取所有的话题 或者 梦话的分类
 * @return array
 * @throws \think\db\exception\DataNotFoundException
 * @throws \think\db\exception\ModelNotFoundException
 * @throws \think\exception\DbException
 */
function getAllNotesType($ty = 1)
{
    $w = array('ty' => $ty);//1话题 2梦话
    $Model = new \app\admin\model\NotesType();
    return $Model->getDataForWheres($w, "id,name", "sorts asc");
}

/**
 * 根据IDS 获取商品
 * @param $ids
 * @type 是否区分上架和下架 0 不区分，1只获取上架的
 * @return array
 * @throws \think\db\exception\DataNotFoundException
 * @throws \think\db\exception\ModelNotFoundException
 * @throws \think\exception\DbException
 */
function getProductListForIds($ids, $type = 0, $field = 'id,name')
{
    if (empty($ids)) {
        return [];
    }
    $list = [];
    $arr = explode(",", $ids);
    $model = new \app\admin\model\Shop();
    for ($i = 0; $i < count($arr); $i++) {
        $w = array(
            'id' => $arr[$i],
            'is_delete' => 0,
        );
        if ($type) {
            $w['stats'] = 0;
        }
        $info = $model->getDataForWhere($w, $field);
        if (!empty($info)) {
            $list[] = $info;
        }
    }
    return $list;
}

/**
 * 过滤用户数据中的多余字段
 * @param $userinfo
 * @param array $fields
 * @return array
 */
function filterUserInfoField($userinfo, $fields = array("first_depid", "group", "depid", 'pwd'))
{
    if (empty($userinfo)) {
        return array();
    }
    for ($i = 0; $i < count($fields); $i++) {
        unset($userinfo[$fields[$i]]);
    }
    return $userinfo;
}


/**
 * 用户金额变动
 * @param $uid 用户ID
 * @param $money 变动金额
 * @param $ty 变动类型 0收入  1支出
 * @param $txt 备注
 * @param $relation_data 关联数据
 * @return bool
 * @throws \think\Exception
 * @throws \think\exception\PDOException
 */
function userMoneyChange($uid, $money, $ty, $txt, $relation_data = "")
{
    $time = time();
    $currTime = date("Y-m-d H:i:s");
    $userInfo = getUserInfoForID($uid);
    if (empty($userInfo)) {
        return false;
    }
    Db::startTrans();
    $totleMoney = $money + $userInfo['money'];
    //增加金额变动明细
    $moneyDetail = array(
        'uid' => $userInfo['id'],
        'money' => $money,
        'y_money' => $totleMoney,
        'ty' => $ty,
        'txt' => $txt,
        'ctime' => time(),
        'relation_data' => $relation_data,
    );
    $moneyDetailModel = Db::table("t_money_detail");
    $moneyDetailModel->insert($moneyDetail);
    $insertId = $moneyDetailModel->getLastInsID();
    if (empty($insertId)) {
        Db::rollback();
        return false;
    }

    //修改用户的总金额

    $userModel = Db::table("t_user");
    $update = array(
        'money' => $totleMoney
    );
    $where = array(
        'uid' => $userInfo['id'],
    );
    $userResult = $userModel->where($where)->update($update);
    if ($userResult || $userResult == 0) {
        Db::commit();
        return true;
    }
    Db::rollback();
    return false;
}

/**
 * 给课程增加奖池 和 购买人数
 * @param $classid
 * @param $money
 * @param $num
 * @return int
 */
function addClasslistTotleMoneyAndNum($classid, $money, $num)
{
    $sql = "update t_classlist set `join` = `join` + {$num} ,totle_money = totle_money + {$money} where id = {$classid}";
    return \think\Db::execute($sql);
}

/**
 * 用户金额变动函数
 * @param $uid 用户ID
 * @param $money 变动金额
 * @param $ty 变动类型 0收入  1支出
 * @param $txt 备注
 * @param $relation_data 关联数据
 * @return bool
 * @throws \think\Exception
 * @throws \think\exception\PDOException
 */
function addUserMoney($uid, $money, $ty, $txt, $relation_data = "")
{
    $time = time();
    $currTime = date("Y-m-d H:i:s");
    Db::startTrans();
    $userInfo = Db::name("user")->lock(true)->where(array('id' => $uid))->find();
    if (empty($userInfo)) {
        Db::rollback();
        return false;
    }
    $y_money = 0;
    if ($ty == 0) {
        $y_money = $userInfo['money'] + $money;
    } else {
        $y_money = $userInfo['money'] - $money;
        if ($y_money < 0) {
            Db::rollback();
            return false;
        }
    }
    //增加金额变动明细
    $moneyDetail = array(
        'uid' => $userInfo['id'],
        'money' => $money,
        'y_money' => $y_money,
        'ty' => $ty,
        'txt' => $txt,
        'ctime' => time(),
        'relation_data' => $relation_data,
    );
    $moneyDetailModel = Db::table("t_money_detail");
    $moneyDetailModel->insert($moneyDetail);
    $insertId = $moneyDetailModel->getLastInsID();
    if (empty($insertId)) {
        Db::rollback();
        return false;
    }

    //修改用户账户余额
    $update = array(
        'money' => $y_money,
    );
    $where = array(
        'id' => $userInfo['id'],
    );
    $resultUser = Db::table("t_user")->where($where)->update($update);
    if ($resultUser || $resultUser == 0) {
        Db::commit();
        return true;
    } else {
        Db::rollback();
        return false;
    }
}


function walletpay($uid, $classInfo, $num, $coupon_id = 0, $coupon_money = 0)
{
    $currTime = getCurrDate();
    Db::startTrans();
    $userInfo = Db::name("user")->lock(true)->where(array('id' => $uid))->find();

    if (empty($userInfo)) {
        Db::rollback();
        return array('err' => 1, 'msg' => '用户不存在');
    }
    if ($userInfo['money'] <= 0) {
        Db::rollback();
        return array('err' => 2, 'msg' => '支付失败，余额不足');
    }
    //计算需要支付的金额
    $money = $classInfo['money'];
    $money = rounding($num * $classInfo['money'] - $coupon_money, 2);
    if ($userInfo['money'] < $money) {
        Db::rollback();
        return array('err' => 3, 'msg' => '支付失败，余额不足');
    }
    //生成定号
    $order_sn = build_order_no();


    //添加订单号
    $orderData = array(
        'order_sn' => $order_sn,
        'uid' => $userInfo['id'],
        'ctime' => $currTime['date'],
        'ptime' => $currTime['date'],
        'stat' => 1,
        'money' => $money,
        'classid' => $classInfo['id'],
        'num' => $num,
        'price' => $classInfo['money'],
        'coupon_id' => $coupon_id,
        'coupon_money' => $coupon_money,
        'pay_type' => 3,
    );
    $payOrderModel = Db::table("t_pay_order");
    $payOrderModel->insert($orderData);
    $insertPayOrderId = $payOrderModel->getLastInsID();
    if (empty($insertPayOrderId)) {
        Db::rollback();
        return array('err' => 4, 'msg' => '支付失败');
    }

    //增加金额变动明细
    $y_money = $userInfo['money'] - $money;
    $moneyDetail = array(
        'uid' => $userInfo['id'],
        'money' => $money,
        'y_money' => $y_money,
        'ty' => 1,
        'txt' => "挑战扣款",
        'ctime' => $currTime['time'],
        'relation_data' => $order_sn,
    );
    $moneyDetailModel = Db::table("t_money_detail");
    $moneyDetailModel->insert($moneyDetail);
    $insertId = $moneyDetailModel->getLastInsID();
    if (empty($insertId)) {
        Db::rollback();
        return array('err' => 5, 'msg' => '支付失败');
    }

    //修改用户账户余额
    $userModel = Db::table("t_user");

    $update = array(
        'money' => $y_money,
    );
    $where = array(
        'id' => $userInfo['id'],
    );
    $resultUser = $userModel->where($where)->update($update);
    if ($resultUser || $resultUser == 0) {
        Db::commit();
        return array('err' => 0, 'msg' => '支付成功', 'data' => $orderData);
    } else {
        Db::rollback();
        return array('err' => 6, 'msg' => '支付失败');
    }

}

/**
 * 验证手机短信验证码是否正确
 * @param $phone 手机号
 * @param $code 短信验证码
 * @param $type 验证码类型 1注册  2 找回密码 3快捷登录 4、绑定支付宝提现账号
 * @return \think\response\Json
 */
function checkPhoneCode($phone, $code, $type)
{

    if (empty($code)) {
        $return['err'] = 10000;
        $return['msg'] = '参数错误,请输入手机短信验证码';
        return $return;
    }
    if (!checkPhone($phone)) {
        $return['err'] = 10001;
        $return['msg'] = '输入的手机号不正确，请输入正确的手机号';
        return $return;
    }
    //判断验证码是否正确
    $tmsgcodeModel = new \app\admin\model\Tmsgcode();
    $tmsgcodeData = $tmsgcodeModel->getDataForWhere(array(
        'tel' => $phone,
        'types' => $type,
    ));

    if (empty($tmsgcodeData)) {
        $return['err'] = 10002;
        $return['msg'] = '短信验证码不存在';
        return $return;
    }
    if ($tmsgcodeData['codes'] != $code) {
        $return['err'] = 10003;
        $return['msg'] = '短信验证码不正确';
        return $return;
    }
    if ($tmsgcodeData['uses'] > 0) {
        $return['err'] = 10004;
        $return['msg'] = '短信验证码已使用';
        return $return;
    }
    $return['err'] = 0;
    $return['msg'] = '验证码正确';
    $return['data'] = $tmsgcodeData;
    return $return;

}

function setPhoneCodeUsed($id)
{
    $tmsgcodeModel = new \app\admin\model\Tmsgcode();
    $tmsgcodeModel->updateDataForWhere(array(
        'mtime' => time(),
        'uses' => 1
    ), array('id' => $id));
}

/**
 * 用户月提现申请，直接扣除账户余额，写入金额变更明细、在写入提现列表 等待系统审核 财务放款
 * @param $applyData
 * @return array
 * @throws \think\Exception
 * @throws \think\db\exception\DataNotFoundException
 * @throws \think\db\exception\ModelNotFoundException
 * @throws \think\exception\DbException
 * @throws \think\exception\PDOException
 */
function userMoneyTxApply($applyData)
{
    Db::startTrans();
    $currTime = getCurrDate();
    $uid = $applyData['uid'];//提现用户
    $money = $applyData['money'];
    $userInfo = Db::name("user")->lock(true)->where(array('id' => $uid))->find();

    if (empty($userInfo)) {
        Db::rollback();
        return array('err' => 1, 'msg' => '用户不存在');
    }
    if ($userInfo['money'] <= 0) {
        Db::rollback();
        return array('err' => 2, 'msg' => '操作失败，余额不足');
    }

    if ($userInfo['money'] < $money) {
        Db::rollback();
        return array('err' => 3, 'msg' => '操作失败，余额不足');
    }

    //增加金额变动明细
    $y_money = $userInfo['money'] - $money;
    $moneyDetail = array(
        'uid' => $userInfo['id'],
        'money' => $money,
        'y_money' => $y_money,
        'ty' => 1,
        'txt' => "余额提现",
        'ctime' => $currTime['time'],
        'relation_data' => "",
        'other_source' => "",
    );
    $moneyDetailModel = Db::table("t_money_detail");
    $moneyDetailModel->insert($moneyDetail);
    $insertId = $moneyDetailModel->getLastInsID();
    if (empty($insertId)) {
        Db::rollback();
        return array('err' => 4, 'msg' => '操作失败');
    }

    //修改用户账户余额
    $userModel = Db::table("t_user");

    $update = array(
        'money' => $y_money,
    );
    $where = array(
        'id' => $userInfo['id'],
    );
    $resultUser = $userModel->where($where)->update($update);
    if ($resultUser || $resultUser == 0) {
        //写入申请记录
        $txapplyModel = Db::table("t_txapply");
        $txapplyModel->insert($applyData);
        $insertId = $txapplyModel->getLastInsID();
        if (empty($insertId)) {
            Db::rollback();
            return array('err' => 5, 'msg' => '操作失败');
        } else {
            Db::commit();
            return array('err' => 0, 'msg' => '操作成功');
        }
    } else {
        Db::rollback();
        return array('err' => 6, 'msg' => '操作失败');
    }

}


function doctorMoneyTxApply($applyData)
{
    Db::startTrans();
    $currTime = getCurrDate();
    $uid = $applyData['uid'];//提现用户
    $money = $applyData['money'];
    $userInfo = Db::name("user")->lock(true)->where(array('id' => $uid))->find();

    if (empty($userInfo)) {
        Db::rollback();
        return array('err' => 1, 'msg' => '用户不存在');
    }
    if ($userInfo['money'] <= 0) {
        Db::rollback();
        return array('err' => 2, 'msg' => '操作失败，余额不足');
    }

    if ($userInfo['money'] < $money) {
        Db::rollback();
        return array('err' => 3, 'msg' => '操作失败，余额不足');
    }

    //增加金额变动明细
    $y_money = $userInfo['money'] - $money;
    $moneyDetail = array(
        'uid' => $userInfo['id'],
        'money' => $money,
        'y_money' => $y_money,
        'ty' => 1,
        'txt' => "余额提现",
        'ctime' => $currTime['time'],
        'relation_data' => "",
        'other_source' => "",
    );
    $moneyDetailModel = Db::table("t_money_detail");
    $moneyDetailModel->insert($moneyDetail);
    $insertId = $moneyDetailModel->getLastInsID();
    if (empty($insertId)) {
        Db::rollback();
        return array('err' => 4, 'msg' => '操作失败');
    }

    //修改用户账户余额
    $userModel = Db::table("t_user");

    $update = array(
        'money' => $y_money,
    );
    $where = array(
        'id' => $userInfo['id'],
    );
    $resultUser = $userModel->where($where)->update($update);
    if ($resultUser || $resultUser == 0) {
        //写入申请记录
        $txapplyModel = Db::table("t_txapply");
        $txapplyModel->insert($applyData);
        $insertId = $txapplyModel->getLastInsID();
        if (empty($insertId)) {
            Db::rollback();
            return array('err' => 5, 'msg' => '操作失败');
        } else {
            Db::commit();
            return array('err' => 0, 'msg' => '操作成功');
        }
    } else {
        Db::rollback();
        return array('err' => 6, 'msg' => '操作失败');
    }

}


/**
 * 获取一个帖子的所有附件信息
 * @param $tid
 * @param $typeid 0帖子 1回复
 * @return array
 * @throws \think\db\exception\DataNotFoundException
 * @throws \think\db\exception\ModelNotFoundException
 * @throws \think\exception\DbException
 */
function getNotesFiles($tid, $typeid = 0, $orderby = "id desc")
{
    if (empty($tid)) {
        return array();
    }
    $model = new \app\admin\model\NotesFiles();
    $w = array('tid' => $tid, 'typeid' => $typeid);

    return $model->getDataForWheres($w, "id,file,thumb,ty,name,ctime,sorts", $orderby);
}

/**
 * 批量获取一个帖子列表的附件数据
 * @param $lists
 * @param $typeid 0帖子附件  1回复附件
 * @return array
 * @throws \think\db\exception\DataNotFoundException
 * @throws \think\db\exception\ModelNotFoundException
 * @throws \think\exception\DbException
 */
function getNotesFilesForLists($lists, $typeid = 0, $orderby = "id desc")
{
    if (empty($lists)) {
        return array();
    }

    foreach ($lists as $key => $val) {
        $lists[$key]['notesFiles'] = getNotesFiles($val['id'], $typeid, $orderby);
    }
    return $lists;
}


/**
 * 一个帖子列表每个帖子是否点赞
 * @param $lists 帖子列表
 * @param $uid 用户ID
 * @return array
 * @throws \think\db\exception\DataNotFoundException
 * @throws \think\db\exception\ModelNotFoundException
 * @throws \think\exception\DbException
 */
function getNotesIsZanForLists($lists, $uid)
{
    if (empty($lists)) {
        return array();
    }
    foreach ($lists as $key => $val) {
        $lists[$key]['isZan'] = getTidIsZan($uid, $val['id']);
    }
    return $lists;
}

/**
 * 一个用户对帖子点赞
 * @param $uid
 * @param $tid
 * @return int
 * @return 0点赞失败 1点赞成功
 * @throws \think\db\exception\ModelNotFoundException
 * @throws \think\exception\DbException
 * @throws \think\db\exception\DataNotFoundException
 */
function notesZan($uid, $tid)
{
    if (empty($uid)) {
        return 0;
    }
    if (empty($tid)) {
        return 0;
    }
    $model = new \app\admin\model\NotesReply();
    $data = ['type' => 1, 'tid' => $tid, 'uid' => $uid, 'ctime' => time()];
    $insertId = $model->add($data);
    if ($insertId) {
        $sql = "update t_notes set praise =praise +1 where id={$tid}";
        \think\Db::execute($sql);
        return 1;
    } else {
        return 0;
    }
}

/**
 * 增加帖子的浏览数量
 * @param $tid
 */
function incNoteReadNum($tid)
{
    $sql = "update t_notes set readnum =readnum +1 where id={$tid}";
    \think\Db::execute($sql);
}

/**
 * 增加商品的浏览数量
 * @param $tid
 */
function incShopReadNum($tid)
{
    $sql = "update t_shop set readnum =readnum +1 where id={$tid}";
    \think\Db::execute($sql);
}


/**
 * 增加帖子的回复数量
 * @param $tid
 */
function incNoteReplyNum($tid)
{
    $sql = "update t_notes set reply =reply +1 where id={$tid}";
    \think\Db::execute($sql);
}

/**
 * 判断uid是否关注了fuid
 * @param $uid
 * @param $fuid
 * @return 关注了返回1 未关注返回0
 */
function isFriend($uid, $fuid)
{
    //100——100
    $keyString = $uid . "_" . $fuid;
    static $lists = array();
    if (empty($uid)) {
        return 0;
    }
    if (empty($fuid)) {
        return 0;
    }
    if (isset($lists[$keyString])) {
        return $lists[$keyString];
    }

    $model = new \app\admin\model\UserFriend();
    $w = ['uid' => $uid, 'fuid' => $fuid];
    $info = $model->getDataForWhere($w);
    if ($info) {
        $lists[$keyString] = 1;
        return 1;
    } else {
        $lists[$keyString] = 0;
        return 0;
    }
}

/**
 * 判断一个用户对一个帖子是否点赞
 * @param $uid用户ID
 * @param $tid帖子ID
 * @return array
 * @return 0未点赞 1已经点赞
 * @throws \think\db\exception\ModelNotFoundException
 * @throws \think\exception\DbException
 * @throws \think\db\exception\DataNotFoundException
 */
function getTidIsZan($uid, $tid)
{
    $keyString = $uid . "_" . $tid;
    static $lists = array();
    if (empty($uid)) {
        return 0;
    }
    if (empty($tid)) {
        return 0;
    }
    if (isset($lists[$keyString])) {
        return $lists[$keyString];
    }
    $model = new \app\admin\model\NotesReply();
    $w = ['type' => 1, 'tid' => $tid, 'uid' => $uid];
    $info = $model->getDataForWhere($w);
    if ($info) {
        $lists[$keyString] = 1;
        return 1;
    } else {
        $lists[$keyString] = 0;
        return 0;
    }
}

/**
 * uid 关注fuid
 * @param $uid
 * @param $fuid
 * @return int
 * @return 1成功 0失败
 * @throws \think\db\exception\ModelNotFoundException
 * @throws \think\exception\DbException
 * @throws \think\db\exception\DataNotFoundException
 */
function addFriend($uid, $fuid)
{
    if (empty($uid)) {
        return 0;
    }
    if (empty($fuid)) {
        return 0;
    }
    $model = new \app\admin\model\UserFriend();
    $data = ['uid' => $uid, 'fuid' => $fuid, 'ctime' => time()];
    $insertId = $model->add($data);
    if ($insertId) {
        $data['ty'] = 0;
        $table = 'user_friend_log';
        $sql = generaSql("t_" . $table, $data);
        \think\Db::query($sql);
        return 1;
    } else {
        return 0;
    }
}

/**
 * 取消关注
 * @param $uid
 * @param $fuid
 * @return 1成功 0失败
 */
function cancelFriend($uid, $fuid)
{
    if (empty($uid)) {
        return 0;
    }
    if (empty($fuid)) {
        return 0;
    }
    $model = new \app\admin\model\UserFriend();
    $data = ['uid' => $uid, 'fuid' => $fuid];
    $flag = $model->delData($data);
    if ($flag) {
        $data['ctime'] = time();
        $data['ty'] = 1;
        $table = 'user_friend_log';
        $sql = generaSql("t_" . $table, $data);
        \think\Db::query($sql);
        return 1;
    } else {
        return 0;
    }
}

/**
 * 生成一个任务的唯一标识
 * @param string $solt盐
 * @return string
 */
function getTaskKey($solt = "")
{
    if (empty($solt)) {
        $solt = mt_rand(100000, 999999);//随机min-max之间的一个值
    }
    return $solt . "" . uniqid();
}


/**
 * 获取所有的加入课程的用户数据
 */
function getAllUserJoin($class_id)
{
    if (empty($class_id)) {
        return array();
    }
    $w = array(
        'classid' => $class_id
    );
    $model = new \app\admin\model\ClassUserjoin();
    return $model->getDataForWheres($w, "*");
}


/**
 *
 * 挑战结算函数，【1、计算总的赢家份数，2、计算每份赢家赢的金额，3、修改该挑战总的赢家份数 4、发放挑战奖励】
 * @param $class_id
 */
function classListReward($class_id)
{

    if (empty($class_id)) {
        return ['err' => 1, 'msg' => "失败,class_id不正确"];
    }

    $allJoinUserLists = getAllUserJoin($class_id);
    if (empty($allJoinUserLists)) {//没有人来加入
        $classListModel = Db::table("t_classlist");

        $update = array(
            'win_num' => 0,
            'is_open_reward' => 1,
            'is_open_reward_time' => time()
        );
        $where = array(
            'id' => $class_id,
        );
        $classListModel->where($where)->update($update);
        return ['err' => 0, 'msg' => "无用户加入"];
    }

    Db::startTrans();
    $classlistInfo = Db::name("classlist")->lock(true)->where(array('id' => $class_id))->find();
    if (empty($classlistInfo)) {
        Db::rollback();
        return ['err' => 1, 'msg' => "失败,class_id不正确"];
    }

    $currDate = getCurrDate();
    if ($classlistInfo['reward_date'] < $currDate['simple']) {
        Db::rollback();
        return ['err' => 1, 'msg' => "失败,未到开奖时间"];
    }

    if ($classlistInfo['is_open_reward'] == 1) {
        Db::rollback();
        return ['err' => 1, 'msg' => "失败,不要重复开奖操作"];
    }


    $totleWinNum = 0;//获取总的赢家份数
    $totleWinMoney = 0;//获取总的赢家付款
    $totleFailNum = 0;//总的失败的份数
    $totleFailMoney = 0;//总的失败的付款
    foreach ($allJoinUserLists as $key => $val) {
        if ($val['is_win'] == 1) {
            $totleWinNum = $totleWinNum + $val['num'];
            $totleWinMoney = $totleWinMoney + $val['money'];
        } else {
            $totleFailNum = $totleFailNum + $val['num'];
            $totleFailMoney = $totleFailMoney + $val['money'];
        }
    }
    $win_lv = 0;//赔率
    if (!empty($totleWinNum)) {
        $win_lv = roundingE(($totleWinMoney + $totleFailMoney) / $totleWinNum / $classlistInfo['money'], 2);
    }
    $per_win_money = roundingE($win_lv * $classlistInfo['money'], 2);//每份收入


    $update = array(
        'win_lv' => $win_lv,
        'win_num' => $totleWinNum,
        'per_win_money' => $per_win_money,
        'is_open_reward' => 1,
        'is_open_reward_time' => time(),
    );
    $where = array(
        'id' => $class_id,
    );
    $resultUser = Db::table("t_classlist")->where($where)->update($update);
    if ($resultUser || $resultUser == 0) {
        /**
         * 发放奖励
         */
        $flag = 0;
        $classUserJoinIds = array();
        foreach ($allJoinUserLists as $key => $val) {
            if ($val['is_win'] == 1) {
                $classUserJoinIds[] = $val['id'];
                $win_money = roundingE($per_win_money * $val['num'], 2);
                $reward_money = roundingE($classlistInfo['reward_money'] * $val['num'], 2);
                $update = array('stat' => 1, 'js_stats' => 1, 'reward_money' => $reward_money, 'win_money' => $win_money, 'win_lv' => $win_lv, 'per_win_money' => $per_win_money);
            } else {
                $update = array('stat' => 2, 'js_stats' => 1, 'is_win' => 2, 'win_lv' => $win_lv, 'per_win_money' => $per_win_money);
            }
            $where = array('id' => $val['id']);
            $resultUser = Db::table("t_class_userjoin")->where($where)->update($update);
            if ($resultUser || $resultUser == 0) {

            } else {
                $flag = 1;
                break;
            }
        }
        if ($flag == 1) {
            Db::rollback();
            return array('err' => 6, 'msg' => '操作失败');
        }
        //写入给用户增加金额队列
        if (!empty($classUserJoinIds)) {
            foreach ($classUserJoinIds as $key => $val) {
                $taskString = json_encode(['path' => "\app\\task\controller\Addusermoneytask#task", "key" => getTaskKey($solt), 'param' => $val]);
                $length = \app\queue\Queue::push(\app\queue\Queue::Addusermoneytask, $taskString);
                if ($length = "" || $length <= 0) {
                    Db::rollback();
                    return array('err' => 6, 'msg' => '操作失败');
                }
            }
        }

        Db::commit();
        return array('err' => 0, 'msg' => '操作成功');

    } else {
        Db::rollback();
        return array('err' => 6, 'msg' => '操作失败');
    }
}


/**
 * 小程序询诊订单结算
 * @param $days 计算几天前的订单
 * @return array
 * @throws \think\Exception
 * @throws \think\db\exception\DataNotFoundException
 * @throws \think\db\exception\ModelNotFoundException
 * @throws \think\exception\DbException
 * @throws \think\exception\PDOException
 */
function hospOrderJs($days = 7, $limit = 50)
{
    $model = new \app\admin\model\HospOrder();
    $selectSecond = strtotime("-" . $days . " day");
    $selectDay = date("Y-m-d", $selectSecond);
    $selectSecond = strtotime($selectDay);

    Db::startTrans();
    $w = [
        'is_delete' => 0,
        'is_js' => 0,
        'stat' => 1,
        'doctor_id' => array('gt', 0),
        'status' => array('in', "3,4"),
        'ptime' => array('lt', $selectSecond)
    ];

    $list = Db::name("hosp_order")->limit($limit)->lock(true)->where($w)->select();
//   echo  Db::name("hosp_order")->getLastSql();//获取上次执行的sql语句

    if (empty($list)) {
        Db::rollback();
        return ['err' => 1, 'msg' => "数据为空"];
    }
    foreach ($list as $key => $val) {
        $js_money = roundingE($val['money'] * $val['js_lv'], 2);
        $update = array(
            'is_js' => 1,
            'js_time' => time(),
            'js_money' => $js_money,
        );
        $where = array(
            'id' => $val['id'],
        );

        $resultUser = Db::table("t_hosp_order")->where($where)->update($update);//修改表要带前缀


        if ($resultUser || $resultUser == 0) {
            addOrderTrackLog(array(
                'ctime' => date("Y-m-d H:i:s"),
                'order_sn' => $val['order_sn'],
                'op_uid' => 0,
                'op_username' => "",
                'act' => "结算订单",
            ));
            $taskString = json_encode(['path' => "\app\\task\controller\Addusermoneytask#htask", "key" => getTaskKey(""), 'param' => $val['id']]);
            $length = \app\queue\Queue::push(\app\queue\Queue::Addusermoneytask, $taskString);

        }
    }

    Db::commit();
    return ['err' => 0, 'msg' => "成功"];


}

/**
 * 结算一个订单
 * @param int $days
 * @param int $limit
 * @return array
 * @throws \think\Exception
 * @throws \think\db\exception\DataNotFoundException
 * @throws \think\db\exception\ModelNotFoundException
 * @throws \think\exception\DbException
 * @throws \think\exception\PDOException
 */
function hospOrderOneJs($ordersn)
{
    $model = new \app\admin\model\HospOrder();


    Db::startTrans();
    $w = [
        'is_delete' => 0,
        'is_js' => 0,
        'stat' => 1,
        'doctor_id' => array('gt', 0),
        'status' => array('in', "3,4"),
        'order_sn' => $ordersn
    ];

    $list = Db::name("hosp_order")->lock(true)->where($w)->select();
//   echo  Db::name("hosp_order")->getLastSql();//获取上次执行的sql语句

    if (empty($list)) {
        Db::rollback();
        return ['err' => 1, 'msg' => "数据为空"];
    }
    foreach ($list as $key => $val) {
        $js_money = roundingE($val['money'] * $val['js_lv'], 2);
        $update = array(
            'is_js' => 1,
            'js_time' => time(),
            'js_money' => $js_money,
        );
        $where = array(
            'id' => $val['id'],
        );

        $resultUser = Db::table("t_hosp_order")->where($where)->update($update);//修改表要带前缀


        if ($resultUser || $resultUser == 0) {
            addOrderTrackLog(array(
                'ctime' => date("Y-m-d H:i:s"),
                'order_sn' => $val['order_sn'],
                'op_uid' => 0,
                'op_username' => "",
                'act' => "结算订单",
            ));
            $taskString = json_encode(['path' => "\app\\task\controller\Addusermoneytask#htask", "key" => getTaskKey(""), 'param' => $val['id']]);
            $length = \app\queue\Queue::push(\app\queue\Queue::Addusermoneytask, $taskString);

        }
    }

    Db::commit();
    return ['err' => 0, 'msg' => "成功"];


}


/**
 * 判断一个用户一个调整是否成功
 * @param $uid 用户ID
 * @param $class_id 课程ID
 * @return array 成功返回true 失败返回false
 */
function checkCheckinStatus($uid, $class_id)
{
    $classMissionModel = new \app\admin\model\ClassCheckin();
    $list = $classMissionModel->getDataForWheres(array(
        'classid' => $class_id,
        'uid' => $uid,
    ), "ctime,type,day", "day asc");
    if (empty($list)) {
        return false;
    }
    $flag = 0;
    foreach ($list as $key => $val) {
        if ($val['type'] == 0) {
            $flag = 1;
            break;
        }
    }
    if ($flag == 1) {
        return false;
    } else {
        return true;
    }
}

/**
 * 对一个课程 一个用户 今日是否需要打卡
 * @param $uid
 * @param $class_id
 * @return  0不需要打卡 1已打卡 2未打卡
 */
function checkTodayIsCheckin($uid, $class_id)
{
    $currDate = getCurrDate();
    $classInfo = getClasslistInfo($class_id);

    //获取今日打卡记录数据
    $where = [
        'classid' => $class_id,
        'uid' => $uid,
        'y' => $currDate['year'],
        'm' => $currDate['month'],
        'd' => $currDate['day'],
    ];
    $classCheckinModel = new \app\admin\model\ClassCheckin();
    $classCheckinInfo = $classCheckinModel->getDataForWhere($where);
    if (empty($classCheckinInfo)) {
        return 0;
    }

    if ($classCheckinInfo['type'] == 1) {
        return 1;
    }
    return 2;
}

/**
 * 写入任务日志表
 * @param $data
 */
function addTaskLog($data)
{
    \think\Db::name("task_log")->data($data)->insert();
}

/**
 * 添加单个用户到消息表中
 * @param $data
 */
function addPushmsgForSingle($data)
{
    $userInfo = getPushUserInfoForId($data['uid'], "a.id as id,a.uname as uname,a.nickname as nickname");
    if (empty($userInfo)) {
        return array('err' => 1, 'msg' => '操作失败，用户未登陆过app,没有查询到推送SESSION');
    }

    if ($data['push_time_type'] == 0) {
        $data['is_avail_push'] = 0;
    } else {
        $data['is_avail_push'] = 1;
    }
    $data = getTengXunPushType($data, $userInfo['tengxun_pushuser_tid'], $userInfo['tengxun_pushuser_os']);
    $pushMsgModel = new \app\admin\model\PushMsg();
    $insertId = $pushMsgModel->add($data);
    if ($insertId) {
        return array('err' => 0, 'msg' => '操作成功', 'allInsertId' => array($insertId));
    } else {
        return array('err' => 1, 'msg' => '操作失败');
    }
}

/**
 * 根据用户ID获取可以推送的用户数据
 * @param unknown $id
 * @param string $fields
 */
function getPushUserInfoForId($uid, $fields = 'a.*')
{
    //echo "----".$id."<br>";
    $sql = "select " . $fields . ",b.tid as tengxun_pushuser_tid,b.os as tengxun_pushuser_os from t_user as a,t_tengxun_pushuser as b where  a.id='" . $uid . "' and a.id = b.uid";
    $userInfo = \think\Db::query($sql);
    if (empty($userInfo)) {
        return array();
    }
    return $userInfo[0];
}

/**
 * @param 按用户类型来获取推送
 * @ty 0所有用户  1非vip用户 2vip用户
 * @param string $fields
 * @return array
 */
function getAllPushUser($ty, $fields = 'a.*')
{
    if ($ty == 0) {
        $sql = "select " . $fields . ",b.tid as tengxun_pushuser_tid,b.os as tengxun_pushuser_os from t_user as a,t_tengxun_pushuser as b where  a.is_delete=0 and a.stat=0 and  a.id = b.uid";
    } else if ($ty == 1) {
        $sql = "select " . $fields . ",b.tid as tengxun_pushuser_tid,b.os as tengxun_pushuser_os from t_user as a,t_tengxun_pushuser as b where  a.is_delete=0 and a.stat=0 and and a.vip=0 and  a.id = b.uid";
    } else if ($ty == 2) {
        $sql = "select " . $fields . ",b.tid as tengxun_pushuser_tid,b.os as tengxun_pushuser_os from t_user as a,t_tengxun_pushuser as b where  a.is_delete=0 and a.stat=0 and and a.vip=1 and  a.id = b.uid";
    }
    if (empty($sql)) {
        return array();
    }

    $lists = \think\Db::query($sql);
    if (empty($lists)) {
        return array();
    }
    return $lists;
}

/**
 * 所有用户到消息表中
 * @ty 0所有用户  1非vip用户 2vip用户
 * @param $data
 */
function addPushmsgForAll($ty, $data)
{
    $userLists = getAllPushUser($ty, "a.id as id,a.uname as uname,a.nickname as nickname");
    if (empty($userLists)) {
        return array('err' => 1, 'msg' => '操作失败，要推送的用户未登陆过app,没有查询到推送SESSION');
    }
    $data['is_avail_push'] = 1;//无需确认，直接可以放入队列推送
    $maxNum = config("txAppPushConfig.maxNum");
    if (empty($maxNum)) {
        return array('err' => 1, 'msg' => '操作失败，未配置单条用户数推送上线');
    }
    $AllInsertData = array();
    $SingleInsertData = array();
    $tempNum = 0;
    $androidTid = [];
    $iosTid = [];
    $iosTestTid = [];

    $androidTidUid = [];
    $iosTidUid = [];
    $iosTestTidUid = [];

    $totleNum = count($userLists);
    $totlePage = ceil($totleNum / $maxNum);
    $currPage = 1;

    foreach ($userLists as $key => $val) {
        $tempNum++;
        if ($val['tengxun_pushuser_os'] == 1) {
            $androidTid[] = $val['tengxun_pushuser_tid'];
            $androidTidUid[] = $val['id'];
        } else if ($val['tengxun_pushuser_os'] == 2) {
            $iosTid[] = $val['tengxun_pushuser_tid'];
            $iosTidUid[] = $val['id'];
        } else if ($val['tengxun_pushuser_os'] == 21) {
            $iosTestTid[] = $val['tengxun_pushuser_tid'];
            $iosTestTidUid[] = $val['id'];
        }
        if ($tempNum >= $totleNum) {//最后一条了
            $SingleInsertData = $data;
            if ($data['push_time_type'] == 0) {
                $SingleInsertData['is_avail_push'] = 0;
            } else {
                $SingleInsertData['is_avail_push'] = 1;
            }

            $SingleInsertData['android'] = implode(",", $androidTid);
            $SingleInsertData['ios'] = implode(",", $iosTid);
            $SingleInsertData['ios_test'] = implode(",", $iosTestTid);
            $SingleInsertData['android_uid'] = implode(",", $androidTidUid);
            $SingleInsertData['ios_uid'] = implode(",", $iosTidUid);
            $SingleInsertData['ios_test_uid'] = implode(",", $iosTestTidUid);
            $SingleInsertData['ty'] = 1;//0单个用户 1多个用户
            $SingleInsertData['push_page'] = $currPage . "/" . $totlePage;
            $SingleInsertData['push_num'] = $tempNum . "/" . $totleNum;
            $allUid = array_merge($androidTidUid, $iosTidUid, $iosTestTidUid);
            $allUid = array_unique($allUid);
            $SingleInsertData['all_uid'] = implode(",", $allUid);
            $AllInsertData[] = $SingleInsertData;
            break;
        }
        if ($tempNum % $maxNum == 0) {//多条
            $SingleInsertData = $data;
            if ($data['push_time_type'] == 0) {
                $SingleInsertData['is_avail_push'] = 0;
            } else {
                $SingleInsertData['is_avail_push'] = 1;
            }
            $SingleInsertData['android'] = implode(",", $androidTid);
            $SingleInsertData['ios'] = implode(",", $iosTid);
            $SingleInsertData['ios_test'] = implode(",", $iosTestTid);
            $SingleInsertData['android_uid'] = implode(",", $androidTidUid);
            $SingleInsertData['ios_uid'] = implode(",", $iosTidUid);
            $SingleInsertData['ios_test_uid'] = implode(",", $iosTestTidUid);
            $SingleInsertData['ty'] = 1;//0单个用户 1多个用户
            $SingleInsertData['push_page'] = $currPage . "/" . $totlePage;
            $SingleInsertData['push_num'] = $tempNum . "/" . $totleNum;
            $allUid = array_merge($androidTidUid, $iosTidUid, $iosTestTidUid);
            $allUid = array_unique($allUid);
            $SingleInsertData['all_uid'] = implode(",", $allUid);

            $AllInsertData[] = $SingleInsertData;
            $currPage++;
            //清空
            $androidTid = [];
            $iosTid = [];
            $iosTestTid = [];
            $androidTidUid = [];
            $iosTidUid = [];
            $iosTestTidUid = [];
            continue;
        }
    }
    $pushMsgModel = new \app\admin\model\PushMsg();
    $allInsertId = array();
    foreach ($AllInsertData as $key => $val) {//循环插入数据并且获取插入ID
        $insertId = $pushMsgModel->addExp($val);
        $allInsertId[] = $insertId;
    }
    if (!empty($allInsertId)) {
        return array('err' => 0, 'msg' => '操作成功', 'allInsertId' => $allInsertId);
    } else {
        return array('err' => 1, 'msg' => '操作失败');
    }
}

function getTengXunPushType($pushMsgInfo, $tid, $os)
{
    if ($os == 1) {
        $pushMsgInfo['android'] = $tid;
    } else if ($os == 2) {
        $pushMsgInfo['ios'] = $tid;
    } else if ($os == 21) {
        $pushMsgInfo['ios_test'] = $tid;
    }
    return $pushMsgInfo;
}

/**
 * 添加APP推送消息到队列中
 * @param $msgId 消息ID
 */
function addPushMsgQueue($msgId)
{
    return \app\queue\Queue::userPush(json_encode(['path' => config("txAppPushConfig.pushMsgTaskPath"), "key" => getTaskKey(), 'param' => $msgId]));
}

function addTaskQueue($taskInfo)
{
    return \app\queue\Queue::systemTaskPush(json_encode(['path' => config("systemTaskConfig.TaskPath"), "key" => getTaskKey(), 'param' => $taskInfo]));
}

/**
 * 加入到系统命令执行表中 等待系统任何执行
 * @param $data
 * @return string
 */
function addRunSystemCommand($data)
{
    return (new \app\admin\model\SystemTaskCli())->add($data);
}

function getNotesIsGuanzhuForLists($lists, $uid)
{
    if (empty($lists)) {
        return array();
    }
    foreach ($lists as $key => $val) {
        $lists[$key]['isGuanzhu'] = isFriend($uid, $val['uid']);
    }
    return $lists;
}

/**
 * 获取状态
 * @param $userInfo
 * @param $dataid
 * @return bool|string
 */
function recordFiles($userInfo, $dataid, $ty = 0)
{
    import("silan.SiLanApi#class", VENDOR_PATH);
    $hander = SiLanApi::getInstance();
    $hander->setDeviceType($ty);
    return $res = $hander->recordFiles($userInfo, $dataid);
}

function getFilesSilanStatus($userInfo, $device, $testid, $ty = 0)
{
    import("silan.SiLanApi#class", VENDOR_PATH);
    $hander = SiLanApi::getInstance();
    $hander->setDeviceType($ty);
    return $res = $hander->getFileStatus($userInfo, $device, $testid);
}

/**
 * 分析数据 Summary
 * @param $thirdData 第三方数据
 * @param $uid 用户ID
 * @return array
 */
function analysisSummaryData($thirdData, $uid, $dataid)
{
    $data = json_decode($thirdData, true);
    $data = $data['result'];
    if (empty($data)) {
        return array('err' => 1, 'msg' => "接口获取数据失败");
    }
    $record = $data['record'];
    $summary = $data['summary'];
    $ahs = $data['ahs'];
    $ecgs = $data['ecgs'];
    $snores = $data['snores'];
    $positions = $data['positions'];
    //判断状态是否是2，如果是2继续分析 如果不是终止
    if ($record['status'] != 1) {
        return array('err' => 1, 'msg' => "文件报告状态未生成");
    }
    $ctime = time();
    $fileStartTime = strtotime($record['start_time']);
    $fileEndTime = strtotime($record['end_time']);

    $sleepData = array();
    $sleepData['uid'] = $uid;
    $sleepData['year'] = date("Y", $fileEndTime);
    $sleepData['month'] = date("m", $fileEndTime);
    $sleepData['day'] = date("d", $fileEndTime);
    $sleepData['year_month_day'] = date("Y-m-d", $fileEndTime);
    $sleepData['start_time'] = formateDate($fileStartTime);//开始睡眠时间
    $sleepData['end_time'] = formateDate($fileEndTime);//结束睡眠时间

    $sleep_time = -1;
    if ($summary['m_dTimeSPT'] >= 0) {
        $sleep_time = $summary['m_dTimeSPT'];
    }
    $sleepData['sleep_time'] = $sleep_time;//睡眠总时间 分钟

    $sleep_status = "";
    if ($summary['sleep_quality'] == "0") {
        $sleep_status = "较差";
    } elseif ($summary['sleep_quality'] == "1") {
        $sleep_status = "欠佳";
    } elseif ($summary['sleep_quality'] == "2") {
        $sleep_status = "尚好";
    } elseif ($summary['sleep_quality'] == "3") {
        $sleep_status = "较好";
    }
    $sleepData['sleep_status'] = $sleep_status;//整体的睡眠状态

    $sleepinterruptions_count = -1;
    if ($summary['m_nSleepInterruptions'] >= 0) {
        $sleepinterruptions_count = $summary['m_nSleepInterruptions'];
    }
    $sleepData['sleepinterruptions_count'] = $sleepinterruptions_count;//总觉醒次数

    $sleep_score = -1;
    if ($summary['sleep_quality_score'] >= 0) {
        $sleep_score = $summary['sleep_quality_score'];
    }
    $sleepData['sleep_score'] = $sleep_score;//总睡眠分数

    $sleep_latency_time = -1;
    if ($summary['m_dTimeFallingAsleep'] >= 0) {
        $sleep_latency_time = $summary['m_dTimeFallingAsleep'];
    }
    $sleepData['sleep_latency_time'] = $sleep_latency_time;//入眠时间

    $sleepData['day_ty'] = nightOrDay($sleepData['start_time'], $sleepData['end_time']);//判断是白天还是夜晚
    $sleepData['sleep_latency_time'] = $sleep_latency_time;//入眠时间

    $apnea_count = -1;
    if (!empty($ahs)) {
        foreach ($ahs as $k => $v) {
            if ($v['record_type'] == 'OA') {
                if ($v['total_totaltimes'] >= 0) {
                    $apnea_count = $v['total_totaltimes'];
                }
                break;
            }
        }
    }
    $sleepData['apnea_count'] = $apnea_count;//呼吸暂停总次数

    $snore_count = -1;
    if (!empty($snores)) {
        if ($snores[0]['times'] >= 0) {
            $snore_count = $snores[0]['times'];
        }
    }
    $sleepData['snore_count'] = $snore_count;//鼾声次数


    $depth_sleep_time = -1;
    if ($summary['m_dTimeSatbleSleep'] >= 0) {
        $depth_sleep_time = $summary['m_dTimeSatbleSleep'];
    }
    $sleepData['depth_sleep_time'] = $depth_sleep_time;//深度睡眠时长

    $depth_sleep_lv = -1;
    if ($summary['m_dPercentSatbleSleep'] >= 0) {
        $depth_sleep_lv = $summary['m_dPercentSatbleSleep'];
    }
    $sleepData['depth_sleep_lv'] = $depth_sleep_lv;//深度睡眠比例


    $middle_sleep_time = -1;
    if ($summary['m_dTimeUnsatbleSleep'] >= 0) {
        $middle_sleep_time = $summary['m_dTimeUnsatbleSleep'];
    }
    $sleepData['middle_sleep_time'] = $middle_sleep_time;//中度睡眠时长


    $middle_sleep_lv = -1;
    if ($summary['m_dPercentUnsatbleSleep'] >= 0) {
        $middle_sleep_lv = $summary['m_dPercentUnsatbleSleep'];
    }
    $sleepData['middle_sleep_lv'] = $middle_sleep_lv;//中度睡眠比例


    $shallow_sleep_time = -1;
    if ($summary['m_dTimeRemSleep'] >= 0) {
        $shallow_sleep_time = $summary['m_dTimeRemSleep'];
    }
    $sleepData['shallow_sleep_time'] = $shallow_sleep_time;//浅度睡眠时长


    $shallow_sleep_lv = -1;
    if ($summary['m_dPercentRemSleep'] >= 0) {
        $shallow_sleep_lv = $summary['m_dPercentRemSleep'];
    }
    $sleepData['shallow_sleep_lv'] = $shallow_sleep_lv;//浅度睡眠比例
    $sleepData['report_ty'] = 1;//1专业报告 0非专业报告

    $fs_count = -1;
    if (!empty($positions)) {
        foreach ($positions as $k => $v) {
            if ($v['times'] >= 0) {
                if ($fs_count == -1) {
                    $fs_count = $v['times'];
                } else {
                    $fs_count += $v['times'];
                }
            }
        }
    }
    $sleepData['fs_count'] = $fs_count;//浅度睡眠比例

    if (!empty($ecgs)) {
        $heartrate_argv = -1;
        $heartrate_min = -1;
        $heartrate_max = -1;
        foreach ($ecgs as $k => $v) {
            if ($v['record_type'] == "平均心率（bmp）") {
                $heartrate_argv = $v['TOTAL'];
            } else if ($v['record_type'] == "最低心率（bmp）") {
                $heartrate_min = $v['TOTAL'];
            } else if ($v['record_type'] == "最高心率（bmp）") {
                $heartrate_max = $v['TOTAL'];
            }
        }
        $sleepData['heartrate_argv'] = $heartrate_argv;//平均心率
        $sleepData['heartrate_min'] = $heartrate_min;//平均心率
        $sleepData['heartrate_max'] = $heartrate_max;//平均心率
    }


    $sleepData['dataid'] = $dataid;//dataid
    $sleepData['summary_data'] = $thirdData;//原始数据
    $sleepData['summary_data_ok'] = 1;
    $model = new \app\admin\model\Sleep();
    $info = $model->getDataForWhere(array(
        'uid' => $uid,
        'dataid' => $dataid
    ));
    if ($info) {
        $res = $model->updateData($sleepData, $info['id']);
        if ($res || $res == 0) {
            return array('err' => 0, 'msg' => "成功");
        } else {
            return array('err' => 1, 'msg' => "失败");
        }
    } else {
        $sleepData['ctime'] = $ctime;
        $res = $model->add($sleepData);
        if ($res > 0) {
            return array('err' => 0, 'msg' => "成功");
        } else {
            return array('err' => 1, 'msg' => "失败");
        }
    }
}


/**
 * 分析数据 Curves
 * @param $thirdData 第三方数据
 * @param $uid 用户ID
 * @return array
 */
function analysisCurvesData($thirdData, $uid, $dataid)
{
    $data = json_decode($thirdData, true);
    if ($data['result'] != 'ok') {
        return array('err' => 1, 'msg' => "接口获取数据失败");
    }

    $ctime = time();
    $sleepData = array();
    /**
     * 整完睡眠状态分时图
     * 测试者整晚睡眠状态的分布，数据类型为：unsigned char。0表示“Null”状态（未知）、
     * 1表示“Stable”状态（稳定睡眠）、2表示“Unstable”状态（不稳定睡眠）、
     * 3表示“REM”状态（快速眼动期）、4表示“Wake”状态（清醒）
     */
    $data['data_sleep_status'];
    /**
     *整晚Apnea事件发生分时图[呼吸暂停]
     * 测试者整晚发生呼吸暂停事件的分布，time_apnea.dat中存放的是Apnea事件发生的位置，data_apnea.dat;
     * 中存放的是发生的Apnea事件持续时间, 位置和时间组合代表一次Apnea事件
     */
    $data['time_apnea'];
    $data['data_apnea'];
    /**
     * 整晚Hypopnea事件发生分时图[低呼吸]
     */
    $data['time_hypopnea'];
    $data['data_hypopnea'];
    /**
     * 整晚心率分时图
     * 测试者整晚测试的心率值的分布，数据类型为：unsigned char，每个数据的间隔时间为1秒。
     * 参数单位：“次/分钟”
     *
     */
    $data['data_ecgRate'];
    /**
     * 整晚体位分时图
     * 测试者整晚体位的分布，数据类型为：unsigned char，每个数据的间隔时间为1秒。
     * 0表示“Null”状态（未知）、1表示“L”状态（左侧卧）、2表示“S”状态（平躺）、3表示“R”状态（右侧卧）、
     * 4表示“P”状态（趴）、5表示“Up”状态（起身）
     */
    $data['data_position'];
    /**
     * 整晚体动分时图
     * 测试者整晚体动强度的分布，是由体动幅度换算出来的一个强度值，该值大于等于0；
     * 体动发生的幅度越大，强度值也就越大。数据类型为：unsigned short int，每个数据的间隔时间为1秒。绘图时，应将数据转换成double型，
     * 具体：将 unsigned short int的值强制类型转换成double后，除以10000.
     */
    $data['data_motion'];
    /**
     * 鼾声事件分时图
     * 测试者整晚的鼾声事件分布，time_snore序列存放的是鼾声事件在时间轴上的开始位置序数，
     * data_snore序列存放的是鼾声事件的持续时间；位置和持续时间的每一个组合代表鼾声事件参数
     */
    $data['time_snore'];
    $data['data_snore'];


    //入库
    $sleepData['curves_data'] = $thirdData;
    $sleepData['curves_data_ok'] = 1;
    $model = new \app\admin\model\Sleep();
    $info = $model->getDataForWhere(array(
        'uid' => $uid,
        'dataid' => $dataid
    ));
    if ($info) {
        $res = $model->updateData($sleepData, $info['id']);
        if ($res || $res == 0) {
            return array('err' => 0, 'msg' => "成功");
        } else {
            return array('err' => 1, 'msg' => "失败");
        }
    } else {
        $sleepData['ctime'] = $ctime;
        $res = $model->add($sleepData);
        if ($res > 0) {
            return array('err' => 0, 'msg' => "成功");
        } else {
            return array('err' => 1, 'msg' => "失败");
        }
    }
}

/**
 * 获取总的数据
 * @param $userInfo
 * @return bool|string
 */
function loadSummary($userInfo, $repid, $ty = 0)
{
    import("silan.SiLanApi#class", VENDOR_PATH);
    $hander = SiLanApi::getInstance();
    $hander->setDeviceType($ty);
    return $res = $hander->loadSummary($userInfo, $repid);
}

/**获取报告数据
 * @param $userInfo
 * @return bool|string
 */
function loadCurves($userInfo, $repid, $ty = 0)
{
    import("silan.SiLanApi#class", VENDOR_PATH);
    $hander = SiLanApi::getInstance();
    $hander->setDeviceType($ty);
    return $res = $hander->loadCurves($userInfo, $repid);
}

function getUserCurrAge($birth)
{
    if (empty($birth)) {
        return '';
    }
    $currtime = time();
    $birth = strtotime($birth . " 00:00:00");
    return changeSecondToDate($currtime - $birth);
}

/**
 * 获取报告状态到队列
 * @param $param
 */
function addSleepReportQueue($param)
{
    $taskString = json_encode(['path' => "\app\\task\controller\Sleepreport#task", "key" => getTaskKey(), 'param' => $param]);
    \app\queue\Queue::push(\app\queue\Queue::SleepReport, $taskString);
}


/**
 * 获取上传文件状态队列
 * @param $param
 */
function addSleepReportQueuePre($param)
{
    $taskString = json_encode(['path' => "\app\\task\controller\Sleepreport#taskpre", "key" => getTaskKey(), 'param' => $param]);
    \app\queue\Queue::push(\app\queue\Queue::SleepReportPre, $taskString);
}

function addSleepReportQueuePre10($param)
{
    $taskString = json_encode(['path' => "\app\\task\controller\Sleepreport#taskpre10", "key" => getTaskKey(), 'param' => $param]);
    \app\queue\Queue::push(\app\queue\Queue::SleepReportPre10, $taskString);
}


/**
 * 获取报告到队列
 * @param $param
 */

function addSleepReportSummaryQueue($param)
{
    $taskString = json_encode(['path' => "\app\\task\controller\Sleepreport#taskloadsummary", "key" => getTaskKey(), 'param' => $param]);
    \app\queue\Queue::push(\app\queue\Queue::SleepReport, $taskString);
}

/**
 * 获取报告报表到队列
 * @param $param
 */

function addSleepReportCurvesQueue($param)
{
    $taskString = json_encode(['path' => "\app\\task\controller\Sleepreport#taskloadcurves", "key" => getTaskKey(), 'param' => $param]);
    \app\queue\Queue::push(\app\queue\Queue::SleepReport, $taskString);
}

/**
 * @return int 0夜晚 1白天
 */
function nightOrDay($start, $end)
{
    $config = config("sleepConfig.night_section");
    $startSecond = strtotime($start);
    $endSecond = strtotime($end);
    $totleMinute = ($endSecond - $startSecond) / 60;
    $returnMinute = 0;
    if (date("Y-m-d", $startSecond) == date("Y-m-d", $endSecond))//同一天
    {

        $startHour = date("H:i", $startSecond);
        $endHour = date("H:i", $endSecond);
        $returnMinute = getDateInterSectionMinute($config, $startHour, $endHour);
    } else//不在同一天
    {
        $startHour = date("H:i", $startSecond);
        $endHour = date("H:i", $endSecond);
        $returnMinute += getDateInterSectionMinute($config, $startHour, "24:00");
        $returnMinute += getDateInterSectionMinute($config, "00:00", $endHour);
    }
    $day_ty = 0;//0夜晚 1白天
    if ($returnMinute >= ($totleMinute / 2)) {
        $day_ty = 0;
    } else {
        $day_ty = 1;
    }
    return $day_ty;

}

/**
 *
 * 把时间转换成分钟
 * @param $hours "17:30"
 */
function hoursToMinute($hours)
{
    if (empty($hours)) {
        return 0;
    }
    $tmpArray = explode(":", $hours);
    return (int)$tmpArray[0] * 60 + $tmpArray[1];
}

/**
 * 获取这个时间段在夜间时间段的分钟数
 * @param $config
 * @param $startHour
 * @param $startMin
 * @param $endHour
 * @param $endMin
 * @return int
 */
function getDateInterSectionMinute($config, $startHour, $endHour)
{
//    echo "<br>-----<br>";
//    echo $startHour."<br>";
//    echo $endHour."<br>";
//    echo "<br>-----<br>";
    if (empty($config)) {
        return 0;
    }
    $returnMin = 0;
    $startHour = hoursToMinute($startHour);
    $endHour = hoursToMinute($endHour);
    foreach ($config as $key => $val) {
        $itemStart = hoursToMinute($val['start']);
        $itemEnd = hoursToMinute($val['end']);
        if ($itemStart > $startHour && $itemStart > $endHour) {
            continue;
        }
        if ($startHour > $itemStart && $startHour > $itemEnd) {
            continue;
        }
        $runStartHour = 0;
        $runEndHour = 0;
        //计算开始时间
        if ($itemStart <= $startHour) {
            $runStartHour = $startHour;
        }
        if ($itemStart > $startHour) {
            $runStartHour = $itemStart;
        }
        //计算结束时间
        if ($itemEnd >= $endHour) {
            $runEndHour = $endHour;
        } else {
            $runEndHour = $itemEnd;
        }
        $temp = $runEndHour - $runStartHour;
//        echo "<br>====<br>";
//        echo $runEndHour . "<br>";
//        echo $runStartHour . "<br>";
//        echo $temp . "<br>";
//        echo "<br>====<br>";
        $returnMin = $returnMin + $temp;

    }

    return (int)$returnMin;
}

/**
 * 确定用户的代理ID 和父级ID
 * @param $tcode 推广者编号
 * @param $acode 代理编号
 * @return array
 */
function userAgentAndParent($tcode, $acode)
{
    $agent_id = 1;//系统默认代码
    $father_id = 0;//系统默认父ID
    /**
     * 如果有代理编号就用设置
     */
    if ($acode) {
        $agentModel = new \app\admin\model\Agent();
        $info = $agentModel->getDataForWhere(array('acode' => $acode));
        if (!empty($info)) {
            $agent_id = $info['id'];
        }
        $userModel = new \app\admin\model\User();
        $userinfo = $userModel->getDataForWhere(array('uname' => $info['uname']));
        if (!empty($userinfo)) {
            $father_id = $userinfo['id'];
        }
    } else {
        if (!empty($tcode)) {
            $userModel = new \app\admin\model\User();
            $userinfo = $userModel->getDataForWhere(array('tcode' => $tcode));
            if (!empty($userinfo)) {
                $father_id = $userinfo['id'];
            }
            if (!empty($userinfo['agent_id'])) {
                $agent_id = $userinfo['agent_id'];
            }
        }
    }

    return array(
        'agent_id' => $agent_id,
        'father_id' => $father_id,
    );
}

/**
 * 获取商品属性函数
 * @param $id
 * @return array
 * @throws \think\db\exception\DataNotFoundException
 * @throws \think\db\exception\ModelNotFoundException
 * @throws \think\exception\DbException
 */
function getGoodAttr($id)
{
    $model = new \app\admin\model\GoodAttribute();
    $w = array(
        'good_id' => $id
    );
    return $model->getDataForWhere($w);
}

/**
 * 获取商品信息
 * @param $goodid
 * @return array
 * @throws \think\db\exception\DataNotFoundException
 * @throws \think\db\exception\ModelNotFoundException
 * @throws \think\exception\DbException
 */
function getGoodInfo($goodid)
{
    $model = new \app\admin\model\Shop();
    return $model->getID($goodid);
}

function getGoodListByOrdersn($order_sn)
{
    $model = new \app\admin\model\OrderGoods();
    $sql = "select b.*,a.num as buy_num,a.money as buy_money,a.attr as buy_good_attr from t_order_goods as a left join t_shop as b on a.good_id = b.id  where a.order_sn='{$order_sn}' order by a.id desc";
    return $list = \think\Db::query($sql, []);

}

/**
 * @param $userInfo 当前用户
 * @param $carList  商品列表
 * @param $totleMoney 商品总金额
 * @param $coupon_id 优惠券ID
 * @param $coupon_money 优惠券金额
 * @return bool
 * @throws \think\Exception
 * @throws \think\db\exception\DataNotFoundException
 * @throws \think\db\exception\ModelNotFoundException
 * @throws \think\exception\DbException
 * @throws \think\exception\PDOException
 */
function addGoodOrder($userInfo, $carList, $userAddrInfo, $user_memo, $totleMoney, $coupon_id, $coupon_money)
{
    $time = time();
    $currTime = date("Y-m-d H:i:s");
    $order_sn = build_order_no();
    $money = rounding($totleMoney - $coupon_money, 2);//订单金额保留两位小数
    //添加订单
    Db::startTrans();

    //增加金额变动明细
    $orderInfo = array(
        'order_sn' => $order_sn,
        'uid' => $userInfo['id'],
        'ctime' => $currTime,
        'stat' => 0,
        'money' => $money,
        'classid' => 0,
        'num' => 0,
        'price' => 0,
        'coupon_id' => $coupon_id,
        'coupon_money' => $coupon_money,
        'ty' => 1,//0是课程 1是商品
        't_name' => $userAddrInfo['t_name'],
        't_phone' => $userAddrInfo['t_phone'],
        't_provice' => $userAddrInfo['t_provice'],
        't_city' => $userAddrInfo['t_city'],
        't_area' => $userAddrInfo['t_area'],
        't_address' => $userAddrInfo['t_address'],
        't_zipcode' => $userAddrInfo['t_zipcode'],
        'pay_type' => 2,
        'status' => 0,
        'user_memo' => $user_memo,
    );

    $payOrderlModel = Db::table("t_pay_order");
    $payOrderlModel->insert($orderInfo);
    $insertId = $payOrderlModel->getLastInsID();
    if (empty($insertId)) {
        Db::rollback();
        return array('err' => 1, 'msg' => '订单添加失败');
    }
    $orderInfo['id'] = $insertId;
    //添加商品
    foreach ($carList as $key => $val) {
        $Model = Db::table("t_order_goods");
        $orderGoods = array(
            'order_sn' => $order_sn,
            'good_id' => $val['id'],
            'good_name' => $val['name'],
            'num' => $val['buy_num'],
            'money' => $val['price'],
            'attr' => $val['buy_good_addr'],
        );
        $Model->insert($orderGoods);
        $insertId = $Model->getLastInsID();
        if (empty($insertId)) {
            Db::rollback();
            return array('err' => 1, 'msg' => '订单添加失败');
        }
    }
    Db::commit();
    return array('err' => 0, 'msg' => '订单添加成功', 'data' => $orderInfo);

}


/**
 * @param $userInfo 当前用户
 * @param $carList  商品列表
 * @param $totleMoney 商品总金额
 * @param $coupon_id 优惠券ID
 * @param $coupon_money 优惠券金额
 * @return bool
 * @throws \think\Exception
 * @throws \think\db\exception\DataNotFoundException
 * @throws \think\db\exception\ModelNotFoundException
 * @throws \think\exception\DbException
 * @throws \think\exception\PDOException
 */
function addGoodOrderYuer($userInfo, $carList, $userAddrInfo, $user_memo, $totleMoney, $coupon_id, $coupon_money)
{
    $time = time();
    $currTime = date("Y-m-d H:i:s");
    $order_sn = build_order_no();
    $money = rounding($totleMoney - $coupon_money, 2);//订单金额保留两位小数

    Db::startTrans();
    $userInfo = Db::name("user")->lock(true)->where(array('id' => $userInfo['id']))->find();
    if (empty($userInfo)) {
        Db::rollback();
        return array('err' => 1, 'msg' => '用户不存在');
    }
    if ($money > $userInfo['money']) {
        Db::rollback();
        return array('err' => 1, 'msg' => '对不起，余额不足');
    }
    //增加订单
    $orderInfo = array(
        'order_sn' => $order_sn,
        'uid' => $userInfo['id'],
        'ctime' => $currTime,
        'ptime' => $currTime,
        'stat' => 1,//1支付成功
        'money' => $money,
        'classid' => 0,
        'num' => 0,
        'price' => 0,
        'coupon_id' => $coupon_id,
        'coupon_money' => $coupon_money,
        'ty' => 1,//0是课程 1是商品
        't_name' => $userAddrInfo['t_name'],
        't_phone' => $userAddrInfo['t_phone'],
        't_provice' => $userAddrInfo['t_provice'],
        't_city' => $userAddrInfo['t_city'],
        't_area' => $userAddrInfo['t_area'],
        't_address' => $userAddrInfo['t_address'],
        't_zipcode' => $userAddrInfo['t_zipcode'],
        'status' => 1,
        'user_memo' => $user_memo,
    );

    $payOrderlModel = Db::table("t_pay_order");
    $payOrderlModel->insert($orderInfo);
    $insertId = $payOrderlModel->getLastInsID();
    if (empty($insertId)) {
        Db::rollback();
        return array('err' => 1, 'msg' => '订单添加失败');
    }
    $orderInfo['id'] = $insertId;
    //添加商品
    foreach ($carList as $key => $val) {
        $Model = Db::table("t_order_goods");
        $orderGoods = array(
            'order_sn' => $order_sn,
            'good_id' => $val['id'],
            'good_name' => $val['name'],
            'num' => $val['buy_num'],
            'money' => $val['price'],
            'attr' => $val['buy_good_addr'],
        );
        $Model->insert($orderGoods);
        $insertId = $Model->getLastInsID();
        if (empty($insertId)) {
            Db::rollback();
            return array('err' => 1, 'msg' => '订单添加失败');
        }
    }
//扣除用户金额
    $result = addUserMoney($userInfo['id'], $money, 1, "挑战扣款", $order_sn);
    if ($result) {
        Db::commit();
        return array('err' => 0, 'msg' => '操作成功', 'data' => $orderInfo);
    } else {
        Db::rollback();
        return array('err' => 1, 'msg' => '操作失败', 'data' => $orderInfo);
    }


}

function addSleepApiLog($uid, $dataid, $ty = 0, $testid = "", $device = "")
{
    $apiLog = (new \app\admin\model\SleepApiLog())->getDataForWhere(['dataid' => $dataid, 'ty' => $ty]);
    if (empty($apiLog)) {
        $data = array(
            'uid' => $uid,
            'dataid' => $dataid,
            'ty' => $ty,//0:100b  1:100c
            'testid' => $testid,
            'device' => $device,
            'ctime' => date("Y-m-d H:i:s"),
        );
        $table = 'sleep_api_log';
        $sql = generaSql("t_" . $table, $data);
        \think\Db::query($sql);
    }
}

function addSleepApiLogPre($uid, $device, $testid, $ty = 0)
{
    $apiLog = (new \app\admin\model\SleepApiLogPre())->getDataForWhere(['device' => $device, "testid" => $testid, 'ty' => $ty, 'is_close' => 0]);
    if (empty($apiLog)) {
        $data = array(
            'uid' => $uid,
            'device' => $device,
            'testid' => $testid,
            'ty' => $ty,//0:100b  1:100c
            'ctime' => date("Y-m-d H:i:s"),
        );
        $table = 'sleep_api_log_pre';
        $sql = generaSql("t_" . $table, $data);
        \think\Db::query($sql);
    }
}

/**
 * 过滤列表中的一个字段的html标签
 * @param $lists
 * @param string $filterFields
 * @return array
 */
function filterHtmlForLists($lists, $filterFields = "content")
{
    if (empty($lists)) {
        return array();
    }
    foreach ($lists as $key => $val) {
        $lists[$key][$filterFields] = strip_tags($val[$filterFields]);
//        $lists[$key][$filterFields] = preg_replace("/<([a-zA-Z]+)[^>]*>/","<\\1>",$val[$filterFields]);
    }
    return $lists;
}

/**生成treeSelect选择框数据
 * @param $lists
 * @return array
 */
function makeTreeSelectData($lists, $checkID = 0)
{

    if (empty($lists)) {
        return [];
    }
    foreach ($lists as $key => $val) {
        $lists[$key]['open'] = true;
        if ($val['id'] == $checkID) {
            $lists[$key]['checked'] = true;
        } else {
            $lists[$key]['checked'] = false;
        }
    }
    $items = array();
    foreach ($lists as $v) {
        $items[$v['id']] = $v;
    }
    $tree = array();
    foreach ($items as $k => $item) {
        if (isset($items[$item['pid']])) {
            $items[$item['pid']]['children'][] = &$items[$k];
        } else {
            $tree[] = &$items[$k];
        }
    }


    return $tree;
}


/**
 * 获取当前毫秒时间蹉
 */
function msectime()
{
    list($msec, $sec) = explode(' ', microtime());
    return (float)sprintf('%.0f', (floatval($msec) + floatval($sec)) * 1000);
}

/**
 * 将数组转成查询字符串
 * @param $paramArr
 * @return string
 */
function createQueryString($paramArr)
{
    if (empty($paramArr)) {
        return '';
    }
    ksort($paramArr);
    return http_build_query($paramArr, '', '&');
}

function hmac_sha1($str, $key)
{
    $signature = "";
    if (function_exists('hash_hmac')) {
        $signature = (hash_hmac("sha1", $str, $key, true));
    } else {
        $blocksize = 64;
        $hashfunc = 'sha1';
        if (strlen($key) > $blocksize) {
            $key = pack('H*', $hashfunc($key));
        }
        $key = str_pad($key, $blocksize, chr(0x00));
        $ipad = str_repeat(chr(0x36), $blocksize);
        $opad = str_repeat(chr(0x5c), $blocksize);
        $hmac = pack(
            'H*', $hashfunc(
                ($key ^ $opad) . pack(
                    'H*', $hashfunc(
                        ($key ^ $ipad) . $str
                    )
                )
            )
        );
        $signature = ($hmac);
    }
    return $signature;
}

/**
 * 获取所有的快递公司数据
 * @return \app\queue\返回队列长度
 */
function getKdCompay()
{
    return config("kdcompanyConfig");
}

function getKdCompayCode($name)
{
    $code = "";
    $list = config("kdcompanyConfig");
    foreach ($list as $key => $val) {
        if ($val['name'] == $name) {
            $code = $val['code'];
            break;
        }
    }
    return $code;
}

/**
 * 查询物流信息
 * @param $compayCode 物流公司编号
 * @param $no 物流单号
 */
function selectWuliuMsg($compayName, $no)
{
    $compayCode = getKdCompayCode($compayName);
    //参数设置
    $key = 'HwYzARHz6105';                        //客户授权key
    $customer = 'FD1A668356CD027598A4D294506E87EB';  //查询公司编号
    $param = array(
        'com' => $compayCode,            //快递公司编码
        'num' => $no,    //快递单号
        'phone' => '',                //手机号
        'from' => '',                //出发地城市
        'to' => '',                    //目的地城市
        'resultv2' => '1'            //开启行政区域解析
    );
    $post_data = array();
    $post_data["customer"] = $customer;
    $post_data["param"] = json_encode($param);
    $sign = md5($post_data["param"] . $key . $post_data["customer"]);
    $post_data["sign"] = strtoupper($sign);
    $url = 'http://poll.kuaidi100.com/poll/query.do';    //实时查询请求地址
    $params = "";
    foreach ($post_data as $k => $v) {
        $params .= "$k=" . urlencode($v) . "&";        //默认UTF-8编码格式
    }
    $post_data = substr($params, 0, -1);
//发送post请求
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_HEADER, 0);
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    $result = curl_exec($ch);
    $data = str_replace("\"", '"', $result);
    $data = json_decode($data, true);
    return $data;
}

/**
 * 增加订单跟踪日志
 */
function addOrderTrackLog($orderTrackLog = array())
{

    $model = Db::table("t_order_track_log");
    $model->insert($orderTrackLog);
}


/**
 * 增加提现跟踪日志
 */
function addTxApplyTrackLog($txApplyTrackLog = array())
{
    $model = Db::table("t_txapply_track_log");
    $model->insert($txApplyTrackLog);
}


function addUserAddress($uid, $address)
{
    $model = new \app\admin\model\UserAddress();
    $data = $address;
    $data['uid'] = $uid;
    $oldAddress = $model->getDataForWhere($data);
    if ($oldAddress) {
        return;
    }
    $model->add($data);
}


/**
 * 获取阿里云物流快递公司列表
 */
function getAlipayKdCompay()
{
    import("myCal.AlipayKdCompany#class", VENDOR_PATH);
    $obj = new AlipayKdCompany();
    return $obj->getAlipayKdCompany();
}


/**
 * 根据快递公司编码获取快递公司信息
 * @param string $code
 * @return array|mixed
 */
function getAlipayKdCompayForCode($code = "")
{
    import("myCal.AlipayKdCompany#class", VENDOR_PATH);
    $obj = new AlipayKdCompany();
    return $obj->getAlipayKdCompanyForCode($code);
}

/**
 * 更具快递单号 和 快递公司编码 查询物流信息
 * @param $no
 * @param $code
 */
function getAlipayKdWuLiuForNo($no, $code)
{
    import("myCal.AlipayKdCompany#class", VENDOR_PATH);
    $obj = new AlipayKdCompany();
    return $obj->select($no, $code);
}

/**
 * 给用户增加角色
 * @param $uid 用户ID
 * @param $gid 角色ID
 */
function addUserSystemGroup($uid, $gid)
{
    $mode = new \app\admin\model\UserGroup();
    $oldInfo = $mode->getDataForWhere(array('uid' => $uid, 'gid' => $gid));
    if (empty($oldInfo)) {
        $mode->add(array('uid' => $uid, 'gid' => $gid, 'ctime' => date("Y-m-d H:i:s")));
    }
}

/**
 * 查询一个用户属于的所有角色
 * @param $uid 用户ID
 */
function getUserAllGroup($uid)
{
    $sql = "select a.* from t_group as a,t_user_group as b where  b.uid='" . $uid . "' and a.id = b.gid";
    $list = \think\Db::query($sql);
    if (empty($list)) {
        return array();
    }
    return $list;
}


/**
 * 是否允许登陆系统
 * @param $groupLists
 * @return int 0不允许  1允许
 */
function is_allow_login_system($groupLists)
{
    if (empty($groupLists)) {
        return 0;
    }
    $flag = 0;
    foreach ($groupLists as $key => $val) {
        if ($val['is_allow_login_system'] == 1) {
            $flag = 1;
            break;
        }
    }
    return $flag;

}

/**
 * 是否又超级管理员权限
 * @param $groupLists
 * @return 0没有  1有
 */
function isSupperManager($groupLists)
{
    $default_supper_manager = 1;
    if (empty($groupLists)) {
        return 0;
    }
    $flag = 0;
    foreach ($groupLists as $key => $val) {
        if ($val['id'] == $default_supper_manager) {
            $flag = 1;
            break;
        }
    }
    return $flag;
}

function getMyAllGoupNameString($groupLists)
{

    if (empty($groupLists)) {
        return "";
    }
    $tempArray = array();
    foreach ($groupLists as $key => $val) {
        $tempArray[] = $val['gname'];
    }
    return implode(",", $tempArray);
}

/**
 * 从session中判断是否是超级管理员
 * @return int
 */
function isSupperManagerForSession()
{
    $UserInfo = Session::get('UserInfo');
    $UserInfo = json_decode($UserInfo, true);
    return $UserInfo['isSupperManager'];
}

/**
 * 获取当前登录用户的session
 * @return int
 */
function getCurrLoginSession()
{
    $UserInfo = Session::get('UserInfo');
    $UserInfo = json_decode($UserInfo, true);
    return $UserInfo;
}

/**
 * 判断当前用户是否是管理员
 * @return 0不是  1是
 */
function isManagerForSession()
{
    $UserInfo = Session::get('UserInfo');
    $UserInfo = json_decode($UserInfo, true);
    $lists = $UserInfo['Group'];
    if (empty($lists)) {
        return 0;
    }
    $flag = 0;
    foreach ($lists as $key => $val) {
        if ($val['is_manager']) {
            $flag = 1;
            break;
        }
    }
    return $flag;
}

/**
 * 获取我管理的角色组
 */
function getMyManagerGroup()
{
    $UserInfo = Session::get('UserInfo');
    $UserInfo = json_decode($UserInfo, true);
    $myGroup = $UserInfo['Group'];
    $isSupperManager = $UserInfo['isSupperManager'];
    if (empty($myGroup)) {
        return array('err' => 1, 'msg' => '该用户未设置所属角色组');
    }
    //获取系统所有角色组
    $allSystemGroup = getAllSystemGroup();
    //获取我可以管理的角色组
    $myManagerGroup = array();
    if ($isSupperManager == 1) {
        $myManagerGroup = $allSystemGroup;
    } else {
        foreach ($myGroup as $key => $val) {
            if ($val['is_manager'] == 1) {//如果是管理员 就要管理比自己级别低的角色组
                foreach ($allSystemGroup as $k => $v) {
                    if ($v['is_manager'] == 1) {
                        if ($v['level'] >= $val['level']) {
                            $myManagerGroup[] = $v;
                        }
                    } else {
                        $myManagerGroup[] = $v;
                    }
                }
            } else {//如果不是管理员 就管理自己的就可以了
                $myManagerGroup[] = $val;
            }
        }
    }
    $myManagerGroup = changeKeyForList($myManagerGroup, "id");
    return $myManagerGroup;

}

/**
 * 获取所有的系统权限组
 */
function getAllSystemGroup()
{
    //获取所有角色组
    $groupModel = new \app\admin\model\Group();
    $groupList = $groupModel->getGroupList("is_manager desc,level asc");
    return $groupList;
}


/**
 * 检查手机号是否正确
 * return 0错误 1正确
 */
function checkPhoneVaild($phonenumber)
{
    if (preg_match("/^1[3456789]{1}\d{9}$/", $phonenumber)) {
        return 1;
    } else {
        return 0;
    }
}


function getHospSection($pid = 0, $fields = "id,name,contents,img")
{
    $model = new \app\admin\model\HospSection();
    $list = $model->getDataForWheres(['is_delete' => 0, 'stats' => 0, 'pid' => $pid], $fields, "sorts asc,id asc");
    return $list;
}

function getAllHospSection($fields = "id,name,contents,img")
{
    $model = new \app\admin\model\HospSection();
    $list = $model->getDataForWheres(['is_delete' => 0, 'stats' => 0], $fields, "sorts asc,id asc");
    return $list;
}

function getLocalCacheKey($table, $type)
{
    $config = config("cacheKey.LocalCacheConfig");
    return $config[$table][$type];

}

function clearLocalCache($table, $id = 0)
{
    $cacheConfig = getLocalCacheKey($table, "info");
    $key = $cacheConfig['key'] . $id;
    setCache($key, [], 0);
    $cacheConfig = getLocalCacheKey($table, "lists");
    $key = $cacheConfig['key'];
    setCache($key, [], 0);
}

function getHospInfo($id, $fields = "id,name,level,contents,img,tel,addr,is_open")
{

    //获取缓存的 键 和缓存时间
    $cacheConfig = getLocalCacheKey("hosptial", "info");
    $key = $cacheConfig['key'] . $id;
    $expire = $cacheConfig['expire'];

    $info = array();
    if (!empty($cacheConfig)) {
        $info = getCache($key);
    }
    if (empty($info)) {
        $info = (new \app\admin\model\HospHospital())->getID($id, $fields);

        setCache($key, $info, $expire);
    }
    $level = config("HOSPTIAL.hosptial_level");//医院等级
    $info['level_info'] = $level[$info['level']];
    return $info;
}

/**
 * 获取医院配置表中的数据
 */
function getHospSysConfig()
{
    $model = new \app\admin\model\HospSysconfig();
    $list = $model->getDataForWheres([], "varname,varvalue,unit,memo,info", "id desc");
    $list = changeArrayKey($list, "varname");
    return $list;
}

function getHospInfoConf()
{
    $hospSection = getAllHospSection();//获取科室
    $hospSection = changeArrayKey($hospSection, 'id');
    return [
        'doctor_level' => config("HOSPTIAL.doctor_level"),//医生等级
        'hosptial_level' => config("HOSPTIAL.hosptial_level"),//医院等级
        'hospSection' => $hospSection,//医院科室
        'hospConfig' => getHospSysConfig()
    ];
}

/**
 * @param $doctorUserInfo
 * @param bool $hosptialFlag 是否取医院信息
 * @return mixed
 */
function changeToDoctor($doctorUserInfo, $hosptialFlag = true)
{
    $config = getHospInfoConf();
    $doctorLevel = $config['doctor_level'];

    $doctorLevel = changeArrayKey($doctorLevel, "id");
    if ($hosptialFlag) {
        $doctorUserInfo['hosp_info'] = getHospInfo($doctorUserInfo['hosp_id']);
    } else {
        $doctorUserInfo['hosp_info'] = array();
    }
    $doctorUserInfo['sect_info'] = $config['hospSection'][$doctorUserInfo['sect_id']]['name'];


    $doctorUserInfo['level_info'] = $doctorLevel[$doctorUserInfo['level']];

    return $doctorUserInfo;
}

function getDoctorInfo($uid, $fields = "id,uid,sect_id,hosp_id,name,img,good_at,contents,av_score,reply_lv,score_lv,service_num,level,is_open_fast,is_open_multi,is_open,fast_service_price_now,fast_service_price,service_price,service_price_now,start_msg,end_msg")
{
    return (new \app\admin\model\HospDoctor())->getDataForWhere(['uid' => $uid], $fields);
}

/**
 * 获取医生对一个订单的未读消息
 * @param $orderinfo
 */
function getDcotorMsgNumNoRead($orderinfo)
{
    $doctor_id = $orderinfo['doctor_id'];
    $model = new \app\admin\model\HospMsg();
    return $model->getCount(['receive_uid' => $doctor_id, 'is_read' => 0, 'order_sn' => $orderinfo['order_sn']]);
}

function getHospOrderInfo($order_sn, $fields = '*')
{
    return (new \app\admin\model\HospOrder())->getDataForWhere(['order_sn' => $order_sn], $fields);
}

function changeDoctorInfoForLists($lists, $key, $fields = "id,uid,sect_id,hosp_id,name,img,good_at,contents,av_score,reply_lv,score_lv,service_num,level")
{
    if (empty($lists)) {
        return array();
    }
    static $allUserinfo = array();//静态变量

    foreach ($lists as $k => $v) {
        $lists[$k]['DoctorInfo'] = array();
        if ($v[$key]) {
            if (!empty($allUserinfo[$v[$key]])) {
                $lists[$k]['DoctorInfo'] = $allUserinfo[$v[$key]];

            } else {
                $userinfo = getDoctorInfo($v[$key], $fields);
                if (!empty($userinfo)) {
                    $allUserinfo[$v[$key]] = $userinfo;
                    $lists[$k]['DoctorInfo'] = $userinfo;
                }
            }
        }
    }

    foreach ($lists as $key => $val) {
        $lists[$key]['DoctorInfo'] = changeToDoctor($val['DoctorInfo'], false);
    }
    return $lists;
}

function getDoctorServiceItem($uid)
{
    $result = array();
    $serviceItemModel = new \app\admin\model\HospServiceItem();
    $userServiceItem = $serviceItemModel->getDataForWheres(['uid' => $uid, 'is_delete' => 0], "*", "sorts asc,id desc");
    if (empty($userServiceItem)) {
        $defaultServiceItemModel = new \app\admin\model\HospDefaultServiceItem();
        $defaultServiceItem = $defaultServiceItemModel->getDataForWheres(['is_delete' => 0], "*", "sorts asc,id desc");
        $result = $defaultServiceItem;
    } else {
        $result = $userServiceItem;
    }
    return $result;
}

/**
 * 计算提供的时间 距离当前时间已经过去了多少时间
 * @param $ptime
 * @return string
 */
function toCurrTime($ptime)
{
    $curr = time();
    $second = $curr - $ptime;//相差的总秒数
    //计算天
    $hdays = floor($second / (3600 * 24));//天
    $second = $second % (3600 * 24);
    //计算小时
    $hhours = floor($second / 3600);//小时
    $second = $second % 3600;

    //计算分钟
    $hminutes = floor($second / 60);//分钟
    $second = $second % 60;

    $str = "";
    if ($hdays) {
        $str .= $hdays . "天";
    }
    if ($hhours) {
        $str .= $hhours . "小时";
    }
    if ($hminutes) {
        $str .= $hminutes . "分钟";
    }
    if ($second) {
        $str .= $second . "秒";
    }
    $str .= "前";
    return $str;
}


/**
 * 获取指定的近期报告
 */
function getNearFile($near_file_ids)
{
    $res = array();
    if (empty($near_file_ids)) {
        return array();
    }
    $ids = array();
    $temp = explode(",", $near_file_ids);
    foreach ($temp as $k => $v) {
        if ($v) {
            $ids[] = $v;
        }
    }
    if (empty($ids)) {
        return array();
    }
    $model = new \app\admin\model\Sleep();
    $lists = $model->getDataForWheres(['id' => array('in', $ids)]);

    foreach ($lists as $key => $val) {
        if ($val['summary_data']) {
            $lists[$key]['summary_data'] = json_decode($val['summary_data'], true);
        } else {
            $lists[$key]['summary_data'] = array();
        }
        if ($val['summary_data']) {
            $lists[$key]['curves_data'] = json_decode($val['curves_data'], true);
        } else {
            $lists[$key]['curves_data'] = arry();
        }
    }
    return $lists;
}

/**
 * 医院订单 的订单状态
 * @param $val
 * @return string
 */
function hospOrderStatus($val)
{
    $str = "";
    if ($val['is_cancel'] == 1) {
        $str = "超时未支付";
    } else {
        if ($val['stat'] == 0) {
            $str = "待支付";
        } else if ($val['stat'] == 2) {
            $str = '退款中';
        } else if ($val['stat'] == 3) {
            $str = '已退款';
        } else if ($val['stat'] == 4) {
            $str = '退款失败';
        } else {
            if ($val['status'] == 0) {
                $str = "待支付";
            } else if ($val['status'] == 1) {
                $str = '待接诊';
            } else if ($val['status'] == 2) {
                $str = '进行中';
            } else if ($val['status'] == 3) {
                $str = '待评价';
            } else if ($val['status'] == 4) {
                $str = '完成';
            } else if ($val['status'] == 5) {
                $str = '取消';
            }
        }
    }

    return $str;
}

/**
 * 获取指定的医嘱报告信息
 * @param $near_file_ids
 * @return array
 * @throws \think\db\exception\DataNotFoundException
 * @throws \think\db\exception\ModelNotFoundException
 * @throws \think\exception\DbException
 */
function getAdviceFile($near_file_ids)
{
    $res = array();
    if (empty($near_file_ids)) {
        return array();
    }
    $ids = array();
    $temp = explode(",", $near_file_ids);
    foreach ($temp as $k => $v) {
        if ($v) {
            $ids[] = $v;
        }
    }
    if (empty($ids)) {
        return array();
    }
    $model = new \app\admin\model\HospDoctorAdvice();
    $lists = $model->getDataForWheres(['id' => array('in', $ids), 'is_delete' => 0]);

    foreach ($lists as $key => $val) {
        $lists[$key]['ctimeFormat'] = date("Y-m-d H:i:s", $val['ctime']);
        $lists[$key]['utimeFormat'] = date("Y-m-d H:i:s", $val['utime']);
    }
    return $lists;
}

/**
 * 把源文件转换成pdf文件
 * @param $source 源文件
 * @param string $dist 目标位置
 * @param string $url 转换成功后的通知url
 * @param string $flag false 进入队列执行， true 立即执行
 * @return \app\queue\返回队列长度
 */
function libreofficeConvertToPDF($source, $dist = "", $url = "", $flag = false)
{
    if (empty($source)) {
        return array('err' => 1);
    }
    $dir = dirname(realpath(APP_PATH));
    $dir = $dir . DIRECTORY_SEPARATOR . 'public';
    if (empty($dist)) {
        $temp = pathinfo($source);
        $dist = $temp['dirname'];
    }
    $command = 'libreoffice --headless --convert-to pdf:writer_pdf_Export ' . $dir . $source . ' --outdir ' . $dir . $dist;
    $data = array(
        'code' => getTaskKey(),
        'cli' => $command,
        'res' => '',
        'ctime' => date("Y-m-d H:i:s"),
        'url' => $url,
        'stats' => 0
    );
    $res = addRunSystemCommand($data);
    if ($res) {
        if ($flag == true) {//立即执行转换
            get_url("http://127.0.0.1:5000/change_to_pdf");
        }
        return array('err' => 0);
    } else {
        return array('err' => 1);
    }
}

function getUserinfoForAccessToken($access_token, $ty, $_hosp)
{
    $model = new \app\admin\model\HospWechatRelation();
    $relationInfo = $model->getDataForWhere(["wechat_access_token" => $access_token, 'ty' => $ty, 'hosp_id' => $_hosp]);

    if (empty($relationInfo)) {
        return array();
    }
    $userModel = new \app\admin\model\User();
    $userInfo = $userModel->getDataForWhere(array('id' => $relationInfo['uid'], 'is_delete' => 0));
    if (empty($userInfo)) {
        return array();
    }
    if ($ty == 1) {
        $userInfo['wechat_access_token'] = $relationInfo['wechat_access_token'];
        $userInfo['wechat_session_key'] = $relationInfo['wechat_session_key'];
    } else {
        $userInfo['dwechat_access_token'] = $relationInfo['wechat_access_token'];
        $userInfo['dwechat_session_key'] = $relationInfo['wechat_session_key'];
    }
    return $userInfo;
}


function getUserinfoForUid($uid, $ty, $_hosp)
{
    $model = new \app\admin\model\HospWechatRelation();
    $relationInfo = $model->getDataForWhere(["uid" => $uid, 'ty' => $ty, 'hosp_id' => $_hosp]);

    if (empty($relationInfo)) {
        return array();
    }
    $userModel = new \app\admin\model\User();
    $userInfo = $userModel->getDataForWhere(array('id' => $relationInfo['uid'], 'is_delete' => 0));
    if (empty($userInfo)) {
        return array();
    }
    if ($ty == 1) {
        $userInfo['wechat_access_token'] = $relationInfo['wechat_access_token'];
        $userInfo['wechat_session_key'] = $relationInfo['wechat_session_key'];
    } else {
        $userInfo['dwechat_access_token'] = $relationInfo['wechat_access_token'];
        $userInfo['dwechat_session_key'] = $relationInfo['wechat_session_key'];
    }
    return $userInfo;
}

/**
 * 小程序订单退款函数
 * @param $order_sn 订单号
 * @param int $tk_money 退款金额 0，就是退全款
 * @param string $refundUrl 回调地址
 * @return mixed
 * @throws \think\db\exception\DataNotFoundException
 * @throws \think\db\exception\ModelNotFoundException
 * @throws \think\exception\DbException
 */
function hospOrderPayRefund($order_sn, $tk_money = 0, $refundUrl = "http://api.dongshuimian.com/api/hosporder/refnotify")
{

    $hospOrder = new \app\admin\model\HospOrder();
    $order_info = $hospOrder->getDataForWhere(array('order_sn' => $order_sn));
    if (empty($order_info)) {

        $return['err'] = 1;
        $return['msg'] = '订单不存在';
        return ($return);
    }
    if ($order_info['stat'] == 3) {
        $return['err'] = 1;
        $return['msg'] = '已经退款，请不要重复退款';
        return ($return);
    }

    if ($order_info['status'] == 2) {
        $return['err'] = 1;
        $return['msg'] = '订单进行中，不能退款';
        return ($return);
    }
    if ($order_info['status'] == 3) {
        $return['err'] = 1;
        $return['msg'] = '订单已完成，不能退款';
        return ($return);
    }

    if ($order_info['status'] == 4) {
        $return['err'] = 1;
        $return['msg'] = '订单已完成，不能退款';
        return ($return);
    }

    if ($order_info['status'] == 0) {
        $return['err'] = 1;
        $return['msg'] = '订单未支付，不能退款';
        return ($return);
    }
    if (empty($tk_money)) {
        $refund_fee = $order_info['money'];//退款金额 元
    } else {
        $refund_fee = $tk_money;
    }

    $Config = config('WEIXIN_APP');
    $Config = $Config[$order_info['hosp_id']];
    $Config = $Config['userClient'];

    $appid = $Config['APPID'];
    $secret = $Config['APPSECRET'];
    $mch_id = $Config['MCHID'];
    $key = $Config['WXKEY'];
    /*-----------------------------------------------------------------------------------*/

    $out_trade_no = $order_info['order_sn'];
    $total_fee = $order_info['money'];
    //$out_refund_no 商户退款单号 自定义而已
    $out_refund_no = $order_sn . 'refund' . time();

    //统一下单退款参数构造
    $unifiedorder = array(
        'appid' => $appid,
        'mch_id' => $mch_id,
        'nonce_str' => getWechatNonceStr(),
        'out_trade_no' => $out_trade_no,
        // out_refund_no 这个建议要唯一，避免出现请求一次，实际退款两次的情况
        'out_refund_no' => $out_refund_no,
        'total_fee' => intval(floatval($total_fee) * 100),
        //此处refund_fee 注意前面不要使用 number_format（）转化成字符串 ，或者更改为： number_format(5000, 2, '.', '')
        'refund_fee' => intval(floatval($refund_fee) * 100),
        'notify_url' => $refundUrl,
    );
    $unifiedorder['sign'] = getWechatMakeSign($unifiedorder, $key);
    //请求数据
    $xmldata = array2xml($unifiedorder);
    $opUrl = "https://api.mch.weixin.qq.com/secapi/pay/refund";
    $res = curl_post_ssl_refund($opUrl, $xmldata, $Config['apiclient_cert'], $Config['apiclient_key']);
    if (!$res) {
        $return['err'] = 1;
        $return['msg'] = '操作失败[接口地址不通]';
        return ($return);
    }
    $content = xml2array($res);
    if (isset($content['result_code']) && strval($content['result_code']) == 'FAIL') {
        $return['err'] = 1;
        $return['msg'] = '操作失败，[' . $content['err_code_des'] . ']';
        return ($return);

    }
    if (isset($content['return_code']) && strval($content['return_code']) == 'FAIL') {
        $return['err'] = 1;
        $return['msg'] = '操作失败，[' . $content['return_msg'] . ']';
        return ($return);
    }
    $return['err'] = 0;
    $return['msg'] = '操作成功';
    $return['data'] = $content;
    return ($return);

}

/**
 * 查询小程序支付 退款 情况
 * @param $order_sn
 * @return mixed
 * @throws \think\db\exception\DataNotFoundException
 * @throws \think\db\exception\ModelNotFoundException
 * @throws \think\exception\DbException
 */
function hospOrderSelectRefund($order_sn)
{

    $hospOrder = new \app\admin\model\HospOrder();
    $order_info = $hospOrder->getDataForWhere(array('order_sn' => $order_sn));
    if (empty($order_info)) {

        $return['err'] = 1;
        $return['msg'] = '订单不存在';
        return ($return);
    }

    if ($order_info['status'] == 0) {
        $return['err'] = 1;
        $return['msg'] = '订单未支付，不能退款';
        return ($return);
    }

    $Config = config('WEIXIN_APP');
    $Config = $Config[$order_info['hosp_id']];
    $Config = $Config['userClient'];

    $appid = $Config['APPID'];
    $secret = $Config['APPSECRET'];
    $mch_id = $Config['MCHID'];
    $key = $Config['WXKEY'];
    /*-----------------------------------------------------------------------------------*/

    $out_trade_no = $order_info['order_sn'];
    $total_fee = $order_info['money'];
    //$out_refund_no 商户退款单号 自定义而已
    $out_refund_no = $order_sn . 'refund' . time();

    //统一下单退款参数构造
    $unifiedorder = array(
        'appid' => $appid,
        'mch_id' => $mch_id,
        'nonce_str' => getWechatNonceStr(),
        'out_trade_no' => $out_trade_no,
    );
    $unifiedorder['sign'] = getWechatMakeSign($unifiedorder, $key);
    //请求数据
    $xmldata = array2xml($unifiedorder);
    $opUrl = "https://api.mch.weixin.qq.com/pay/refundquery";
    $res = curl_post_ssl_refund($opUrl, $xmldata, $Config['apiclient_cert'], $Config['apiclient_key']);
    if (!$res) {
        $return['err'] = 1;
        $return['msg'] = '操作失败[接口地址不通]';
        return ($return);
    }
    $content = xml2array($res);
    $return['err'] = 0;
    $return['msg'] = '操作成功';
    $return['data'] = $content;
    return ($return);

}

/**
 * 微信小程序支付 退款request请求函数
 * @param $url
 * @param $vars
 * @param int $second
 * @param array $aHeader
 * @return bool|mixed
 */
function curl_post_ssl_refund($url, $vars, $apiclient_cert, $apiclient_key, $second = 30, $aHeader = array())
{
    $ch = curl_init();
    //超时时间
    curl_setopt($ch, CURLOPT_TIMEOUT, $second);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    //这里设置代理，如果有的话
    //curl_setopt($ch,CURLOPT_PROXY, '10.206.30.98');
    //curl_setopt($ch,CURLOPT_PROXYPORT, 8080);
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
    //TODO 以下两种方式需选择一种
    /*------- --第一种方法，cert 与 key 分别属于两个.pem文件--------------------------------*/
    //默认格式为PEM，可以注释
    //curl_setopt($ch,CURLOPT_SSLCERTTYPE,'PEM');
    $dir = dirname(realpath(APP_PATH));
    $apiclient_cert = $dir . $apiclient_cert;
    $apiclient_key = $dir . $apiclient_key;
    curl_setopt($ch, CURLOPT_SSLCERT, $apiclient_cert);
    //默认格式为PEM，可以注释
    //curl_setopt($ch,CURLOPT_SSLKEYTYPE,'PEM');
    curl_setopt($ch, CURLOPT_SSLKEY, $apiclient_key);
    /**
     * 补充 当找不到ca根证书的时候还需要rootca.pem文件
     * TODO 注意，微信给出的压缩包中，有提示信息：
     *      由于绝大部分操作系统已内置了微信支付服务器证书的根CA证书,
     *      2018年3月6日后, 不再提供CA证书文件（rootca.pem）下载
     */
    //curl_setopt($ch, CURLOPT_CAINFO,'/mnt/www/Public/certxxxxxxxxxxxxxxxxxxxx755/rootca.pem');

    /*----------第二种方式，两个文件合成一个.pem文件----------------------------------------*/
    //curl_setopt($ch,CURLOPT_SSLCERT,getcwd().'/all.pem');

    if (count($aHeader) >= 1) {
        curl_setopt($ch, CURLOPT_HTTPHEADER, $aHeader);
    }

    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $vars);
    $data = curl_exec($ch);
    if ($data) {
        curl_close($ch);
        return $data;
    } else {
        $error = curl_errno($ch);
        //echo "call faild, errorCode:$error\n";
        curl_close($ch);
        return false;
    }
}


/**
 * 微信提现到用户的 钱包余额
 * @param $order_sn
 * @param $money
 * @param $openid
 * @param string $check_name
 * @param string $re_user_name
 * @param string $desc
 * @return mixed
 * @throws \think\db\exception\DataNotFoundException
 * @throws \think\db\exception\ModelNotFoundException
 * @throws \think\exception\DbException
 */
function wechatCompanyPayUser($hosp_id, $order_sn, $money, $openid, $check_name = "NO_CHECK", $re_user_name = "", $desc = "提现")
{


    $Config = config('WEIXIN_APP');
    $Config = $Config[$hosp_id];
    $Config = $Config['userClient'];

    $appid = $Config['APPID'];
    $secret = $Config['APPSECRET'];
    $mch_id = $Config['MCHID'];
    $key = $Config['WXKEY'];
    /*-----------------------------------------------------------------------------------*/
    //统一下单退款参数构造
    $unifiedorder = array(
        'mch_appid' => $appid,
        'mchid' => $mch_id,
        'nonce_str' => getWechatNonceStr(),
        'partner_trade_no' => $order_sn,//商户订单号，需保持唯一性
        'openid' => $openid,//商户appid下，某用户的openid
        'check_name' => $check_name,//NO_CHECK：不校验真实姓名 FORCE_CHECK：强校验真实姓名
        're_user_name' => $re_user_name,//收款用户真实姓名。如果check_name设置为FORCE_CHECK，则必填用户真实姓名
        'amount' => $money * 100,//企业付款金额，单位为分
        'desc' => $desc,//企业付款备注，必填。注意：备注中的敏感词会被转成字符*
    );
    $unifiedorder['sign'] = getWechatMakeSign($unifiedorder, $key);
    //请求数据
    $xmldata = array2xml($unifiedorder);
    $opUrl = "https://api.mch.weixin.qq.com/mmpaymkttransfers/promotion/transfers";
    $res = curl_post_ssl_refund($opUrl, $xmldata, $Config['apiclient_cert'], $Config['apiclient_key']);
    if (!$res) {
        $return['err'] = 1;
        $return['msg'] = '操作失败[接口地址不通]';
        return ($return);
    }
    $content = xml2array($res);
    $return['err'] = 0;
    $return['msg'] = '操作成功';
    $return['data'] = $content;
    return ($return);

}

/**
 * 给小程序用户发送客服消息
 * @param $msg =['touser'=>'openid','msgtype'=>'消息类型','content'=>'消息内容']
 * @param int $hosp_id
 * @param string $client 1患者  2是医生
 * @return \think\response\Json
 */
function sendWechatCustomerServiceMsg($msg, $hosp_id = 0, $client = "1")
{
    $Config = config('WEIXIN_APP');
    $Config = $Config[$hosp_id];
    if ($client == 1) {
        $Config = $Config['userClient'];
    } else {
        $Config = $Config['doctorClient'];
    }
    $appid = $Config['APPID'];
    $secret = $Config['APPSECRET'];
    $access_token = getCache("wechatToken");
    if (empty($access_token)) {
        $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={$appid}&secret={$secret}";
        $data = httpCurl($url, "GET", []);

        $data = json_decode($data, true);

        if ($data['access_token']) {
            setCache("wechatToken", $data['access_token'], 7200);
            $access_token = $data['access_token'];
        } else {
            return ['err' => 1, 'data' => [], 'msg' => $data['errmsg'] . "[access_token获取失败]"];
        }
    }

    $url = "https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=" . $access_token;

    if ($msg['msgtype'] == 'text') {//发送文本消息内容

        $arr = [
            'touser' => $msg['touser'],
            'msgtype' => 'text',
            'content' => $msg['content'],
        ];

        $data = json_encode($arr, JSON_UNESCAPED_UNICODE);
        $resData = httpCurl($url, "POST", $data);
        $resData = json_decode($resData, true);
        if ($resData['errcode'] == '45015') {
            return ['err' => 1, 'data' => [], 'msg' => '发送失败'];
        }
        return ['err' => 0, 'data' => [], 'msg' => '发送成功'];


    }
    if ($msg['msgtype'] == 'image') {//发送图片消息

        $arr = [
            'touser' => $msg['touser'],
            'msgtype' => 'image',
            'image' => ['media_id' => $msg['media_id']],
        ];
        $data = json_encode($arr, JSON_UNESCAPED_UNICODE);
        $resData = httpCurl($url, "POST", $data);
        $resData = json_decode($resData, true);
        if ($resData['errcode'] == '45015') {
            return ['err' => 1, 'data' => [], 'msg' => '发送失败'];
        }
        return ['err' => 0, 'data' => [], 'msg' => '发送成功'];

    }
    if ($msg['msgtype'] == 'link') {//发送图文链接

        $arr = [
            'touser' => $msg['touser'],
            'msgtype' => 'link',
            'link' => ['title' => $msg['title'], 'description' => $msg['description'], 'url' => $msg['url'], 'thumb_url' => $msg['thumb_url']],
        ];
        $data = json_encode($arr, JSON_UNESCAPED_UNICODE);
        $resData = httpCurl($url, "POST", $data);
        $resData = json_decode($resData, true);
        if ($resData['errcode'] == '45015') {
            return ['err' => 1, 'data' => [], 'msg' => '发送失败'];
        }
        return ['err' => 0, 'data' => [], 'msg' => '发送成功'];

    }
    if ($msg['msgtype'] == 'miniprogrampage') {//发送小程序卡片

        $arr = [
            'touser' => $msg['touser'],
            'msgtype' => 'link',
            'miniprogrampage' => ['title' => $msg['title'], 'pagepath' => $msg['pagepath'], 'thumb_media_id' => $msg['thumb_media_id']],
        ];
        $data = json_encode($arr, JSON_UNESCAPED_UNICODE);
        $resData = httpCurl($url, "POST", $data);
        $resData = json_decode($resData, true);
        if ($resData['errcode'] == '45015') {
            return ['err' => 1, 'data' => [], 'msg' => '发送失败'];
        }
        return ['err' => 0, 'data' => [], 'msg' => '发送成功'];

    }


}

function httpCurl($url, $type, $data = [])
{
    $curl = curl_init();
    curl_setopt($curl, CURLOPT_URL, $url);
    if ($type == 'GET') {
//        curl_setopt($curl, CURLOPT_HEADER, 1);        //设置头文件的信息作为数据流输出
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);//设置获取的信息以文件流的形式返回，而不是直接输出
    }
    if ($type == 'POST') {
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($curl, CURLOPT_POST, 1);
        curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
    }
    $res = curl_exec($curl);
    curl_close($curl);
    return $res;
}


/**
 * 微信小程序 获取手机号 解密函数
 * @param $encryptedData
 * @param $iv
 */
function WechatPhoneDecrpt($encryptedData, $iv, $sessionKey, $hosp_id)
{

    $Config = config('WEIXIN_APP');
    $Config = $Config[$hosp_id];
    $Config = $Config['userClient'];

    $appid = $Config['APPID'];
    $secret = $Config['APPSECRET'];
    $mch_id = $Config['MCHID'];
    $key = $Config['WXKEY'];


    include_once(dirname(realpath(APP_PATH)) . "/vendor/myCal/WXBizDataCrypt.php");
    $data = '';
    $pc = new WXBizDataCrypt($appid, $sessionKey);
    $errCode = $pc->decryptData($encryptedData, $iv, $data);

    if ($errCode == 0) {
        return json_decode($data, true);
    } else {
        return array();
    }

}

function getAllNewwindProduct()
{
    $rlists = array();
    $model = new \app\admin\model\NewwindProduct();
    $lists = $model->getDataForWheres([], "id,name,productkey", "sorts asc");
    if (!empty($lists)) {
        $rlists = $lists;
    }
    $rlists = changeKeyForList($rlists, 'id');
    return $rlists;
}

/**
 * 富文本内容中的图片增加url域名前缀
 * @param $contents 富文本内容
 * @param $pre url前缀
 */
function dealContentsForImages($contents, $url_pre)
{
    return preg_replace('/(<img.+?src=")(.*?)/', '$1' . $url_pre . '$2', $contents);
}
/**
 * 富文本内容中的图片增加url域名前缀增强版
 * @param $contents 富文本内容
 * @param $pre url前缀
 */
function dealContentsForImagesE($contents, $url_pre)
{

    $newImg = preg_replace_callback('/(<img.+?src=")(?!http:\/\/)(?!https:\/\/)(.*?)/', function ($matches) use ($url_pre) {
            return $matches[1] . $url_pre . $matches[2];
        }, $contents);
    return $newImg;
}

